【问题标题】:vue, binding two values from selected option by v-modelvue,通过 v-model 绑定来自所选选项的两个值
【发布时间】:2020-03-15 10:23:42
【问题描述】:

我有一个工作的 vue/laravel 组件,我在选择框中使用 v-for 循环,以便从 vue 数组创建选项。这可以正常工作。

我的 v-bind 将所选选项的 id 正确绑定到 featureID,但这是我的问题:

我怎样才能将 feature.feature_name 绑定到另一个 prop,比如 featureName?

我看不到如何将所选选项的 ID 和名称绑定到两个不同的道具?

<select v-model="featureID">
  <option v-for="feature in features" v-bind:value="feature.id">
    @{{ feature.name }}
  </option>
</select>

data: {
    featureID: [''],
    features: [{id:1, name: 'test'}, {id:2, name: 'good}]
}

【问题讨论】:

  • 我假设你的意思是 feature.name 和 feature.id,对吧?这就是与您的数据集匹配的内容。
  • 对不起@user1015214,错字。刚刚修好了

标签: javascript vue.js


【解决方案1】:

你不能在一个选项标签中传递多个值,但你可以做的是传递整个对象作为值。你只需要传递feature 作为道具

<select v-model="featureID">
  <option v-for="feature in features" v-bind:value="feature">
    @{{ feature.name }}
  </option>
</select>

data: {
    featureID: [''],
    features: [{id:1, name: 'test'}, {id:2, name: 'good}]
}

然后您将拥有整个对象,并且您将能够获取 id 和/或名称。

这是JSFiddle

【讨论】:

    【解决方案2】:

    您可以使用所选列表项的索引来代替id 的功能。

    <select v-model="selectedIdx">
      <option v-for="(feature, index) in features" v-bind:value="index" :key="index">
        @{{ feature.name }}
      </option>
    </select>
    
    data: {
      selectedIdx: null,
      features: [
        {id:1, name: 'test'},
        {id:2, name: 'good'},
      ]
    },
    computed: {
      selectedFeature() {
        return this.features[this.selectedIdx]
      } 
    }
    

    访问selectedFeature 你已经选择了特征对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-15
      • 2021-06-08
      • 2021-11-17
      • 2020-09-13
      • 2019-07-28
      • 2021-03-18
      • 2021-08-26
      • 2023-03-17
      相关资源
      最近更新 更多