【问题标题】:vue.js loop option value in object对象中的 vue.js 循环选项值
【发布时间】:2020-06-02 07:58:22
【问题描述】:

我有这样的对象;

fluit:[
    {id:'001', name:"Apple"},
    {id:'002', name:"Banana"},
    {id:'003', name:"Mango"},
    {id:'004', name:"orange"},
    {id:'005', name:"papaya"},
  ]

vuejs 中的代码是这样的

<select >
  <option v-for="(item, index) in fluit" :key="index" :value="item.id" id="select"{{item.name</option>
</select>

我从这个标签得到的结果是这样的

我想问的是如何将值作为每个选项的 id。就像我选择 Mango 并且值为 003 时一样。 如果你知道如何解决这个问题,请帮助我。 谢谢。

【问题讨论】:

标签: javascript vue.js


【解决方案1】:

为您的解决方案使用这个 -

<template>
    <select name="itemType" v-model="itemType" @change="onChange()" class="form-control">
         <option value="001">Apple</option>
         <option value="002">Banana</option>
    </select>
</template>

<script>
export default {
    data() {
        return {
            itemType: '',
        }
    },

    methods: {
        onChange() {
            console.log('The new value is: ', this.itemType)
        }
    }
}
</script>

我的建议是使用 vuetify (v-select) 组件和 vue 以获得更好的性能。

<template>
     <v-select
        v-model="select"
        :items="fluit"
        item-text="id"
        item-value="name"
        label="Select"
        @input="doSomething"
        return-object/>
</template>

<script>
  export default {
    data () {
      return {
        select: { id:'005', name:"papaya" },
        items: [
           {id:'001', name:"Apple"},
           {id:'002', name:"Banana"},
           {id:'003', name:"Mango"},
           {id:'004', name:"orange"},
           {id:'005', name:"papaya"},
        ],
      }
method:{
      doSomething(){
       console.log(this.select)
      }
    }

    },
  }
</script>

我希望它会有所帮助!

【讨论】:

    【解决方案2】:

    将 v-model 添加到您的选择中,就是这样:

    <select v-model="selectedItem">
      <option v-for="(item, index) in fluit" :key="index" :value="item.id" id="select"> 
       {{item.name}}
      </option>
    </select>
    

    现在 selectedItem 将包含水果的值,工作示例: https://codesandbox.io/s/fruit-select-vs709

    【讨论】:

    • 嗨,亲爱的,谢谢你,我知道了。你太有帮助了
    猜你喜欢
    • 2018-08-08
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 2016-08-11
    相关资源
    最近更新 更多