Search code examples
vue.jsv-for

How to get ID from object when using Vue v-for


I have a select with options created using a Vue.js v-for loop. This works fine but the issue I am having is taking and ID of the option and assigning that to my v-model

What's in my data property

mplans: [
    {
        name: 'silver',
        id: 'silver-m-2019-07-16'
    },
    {
        name: 'gold',
        id: 'gold-m-2019-07-16'
    },
],

My select

<select class="form-control" v-model="plan">
    <option disabled hidden>Select A Plan</option>
    <option v-for="plan in mplans">{{ plan.name }} - Monthly</option>   
</select>

Solution

  • You can do this to get the ID from the selected option

    <select class="form-control" v-model="plan">
        <option disabled hidden value="">Select A Plan</option>
        <option v-for="p in mplans" :value="p.id" :key="p.id">
           {{ p.name }} - Monthly
        </option>   
    </select>
    

    Note: I've changed the v-for "plan" for "p", it can be ambiguous