how to get value out of v-for loop in <select> and <option>

Viewed 222

I am looking for a way to get a value out of a v-for loop. Can anyone help me with this? I have the following code:

Select Country:
        <select @change="selectCountryStats(country.code)">
            <option
                v-for="country in everyCountry"
                :key="country.name"
                value="country.name"
                
            >
                {{ country.name }}
            </option>
        </select>

and in @change I would like to get the value of country.code, but this value is first known, when the v-for loop is triggered, which is not the case.

Any solution for this problem will be appreaciated.

1 Answers

You can't use the v-for's iterator outside of the v-for loop because it's out of scope.

For the change-event handler to receive the country code, you'd have to change the <option>.value bindings from country.name to country.code:

<option :value="country.code">

For inline event handlers, the event parameter is stored in a special $event variable. And since the change event's target is the <select>, you could access the new value (the country code of the selection) in the change-event handler via $event.target.value:

<select @change="selectCountryStats($event.target.value)">

new Vue({
  el: '#app',
  data: () => ({
    everyCountry: [
      {
        name: 'United States',
        code: 'US'
      },
      {
        name: 'Canada',
        code: 'CA'
      },
    ]
  }),
  methods: {
    selectCountryStats(e) {
      console.log(e)
    }
  }
})
<script src="https://unpkg.com/vue@2.6.12/dist/vue.min.js"></script>

<div id="app">
  <select @change="selectCountryStats($event.target.value)">
    <option
            v-for="country in everyCountry"
            :key="country.name"
            :value="country.code"

            >
      {{ country.name }}
    </option>
  </select>
</div>

Related