【问题标题】:Using :selected binding on select with bound value在具有绑定值的选择上使用 :selected 绑定
【发布时间】:2021-12-18 12:31:41
【问题描述】:

我想根据它的值来选择一个标签,这没什么特别的,直接使用就可以了。

<select id="some-select" @input="doSomething($event.target.value)">
  <option value="example" :selected="dependency === 'example'">A Name</option>
  <option value="anotherOne" :selected="dependency === 'anotherOne'">Another Name</option>
</select>

现在我想重构我的代码并为基本输入创建一些可重用的组件。所以我创建了一个自定义选择。问题来了: 我需要输入/选择才能使用 v-model。因此我在select 上有一个:value="modelValue" 绑定。这将覆盖选定的状态,即使它匹配并且选定的状态为真。

问题是:我如何才能解决 :selected 绑定并将 modelValue 最初设置为匹配的 option

由于 modelValue 是(并且必须是)一个道具,我不能直接在组件中编写它。

<custom-select :selection-set="availableOptions" :is-seamless="true" :selected-value="dependency"
      @input="doSomething($event.target.value)"/>

组件:

<template>
  <div class="select-wrapper">
    <select :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" :id="displayName" :class="classObject" :style="styleObject">
      <option v-for="(option, index) in selectionSet" :key="index" :value="option.value" :selected="option.value === selectedValue">{{option.name}}</option>
    </select>
  </div>
</template>
<script>
export default {
  name: 'custom-select',
  props: {
    // ... various others, not important for given problem
    selectionSet: {
      type: Array, // The Array struct looks like: [{name: 'xy', value: 'xy'}, ...]
      required: true,
    },
    selectedValue: {
      type: String, // Is the same as dependency in the non component variation.
      required: false,
    },
  },
};
</script>

【问题讨论】:

    标签: vue.js vue-component vuejs3


    【解决方案1】:

    对于文档:

    我通过在 &lt;custom-select&gt; 调用上传递 modelValue 属性的初始值解决了这个问题。

    <custom-select :model-value="dependency" :selection-set="availableOptions" :is-seamless="true" :selected-value="dependency"
      @input="doSomething($event.target.value)"/>
    

    并摆脱组件内的:selected 绑定。

    【讨论】:

      猜你喜欢
      • 2015-05-10
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-06
      • 1970-01-01
      相关资源
      最近更新 更多