Home > Net >  How can i get :key value in v-for loop in a variable?
How can i get :key value in v-for loop in a variable?

Time:06-02

In Vuejs, how can i get :key value which stores value from v-for loop in a dropdown. I am trying to get id of dropdown along with the name. I can get name using @change>event.target.value but is there any possibility to get key value?

Thanks

<select @change="checkFirst($event)" v-model="firstDropdownValue">
   <option value="none" selected="selected"> Select one...</option>
   <option 
      v-for="data in getCategoriesDetail" 
      :key="data.id" :
      :value="data.name">{{data.name}}</option>
</select>

CodePudding user response:

You can simply use the v-model you use in your select ! And you should use the entire object in the :value instead of just the name :value="data" and then use it in the template as firstDropdownValue.name

new Vue({
  el: "#app",
  data: () => ({
    firstDropdownValue: null,
    getCategoriesDetail: [
      {id:1, name: "foo"},
      {id:2, name: "bar"},
      {id:3, name: "baz"},
    ]
  }),
  
  methods: {
    checkFirst(){
      console.log(this.firstDropdownValue)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <select @change="checkFirst" v-model="firstDropdownValue">
    <option value="none" selected="selected"> Select one...</option>
    <option 
    v-for="data in getCategoriesDetail" 
    :key="data.id"
    :value="data"
    >{{data.name}}</option>
  </select>
  
  Selected value : {{firstDropdownValue && firstDropdownValue.name}}
</div>

CodePudding user response:

As per my understanding, You want to get the value of :key which is data.id of the selected option from the dropdown. If Yes, You can use v-model to get the whole object instead of just name and then you can filtered out the properties you want in the script.

Demo :

new Vue({
  el: '#app',
  data: {
    getCategoriesDetail: [{
        id: 1,
      name: 'Option 1'
    }, {
        id: 2,
      name: 'Option 2'
    }, {
        id: 3,
      name: 'Option 3'
    }, {
        id: 4,
      name: 'Option 4'
    }],
    firstDropdownValue: 'none'
  },
  methods: {
    checkFirst() {
        console.log('id : '   this.firstDropdownValue.id)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <select @change="checkFirst" v-model="firstDropdownValue">
    <option value="none">Select one...</option>
    <option 
            v-for="item in getCategoriesDetail" 
            :key="item.id"
            :value="item">{{ item.name }}</option>
  </select>
</div>

  • Related