Skip to content
Advertisement

Populate using v-for loop in VueJS

I am new to VueJS and I just figure out how to populate Select Options box using v-for loop.

<select>
    <option v-for="person in persons" :value="personid">{{ personname }}</option>
</select>

Here is the list I have.

"persons": {
        "2": "Person1",
        "3": "Person2",
        "4": "Person3"
    }

This is our desired output.

<select id="persons">
    <option value="3">Person1</option>
    <option value="4">Person2</option>
</select>

Advertisement

Answer

Luckily for you, Vue can loop through the properties in an Object as described in v-for with an Object.

I’ve also included a snippet below which should help you achieve what you want.

Vue.config.productionTip = false;
Vue.config.devtools = false;

new Vue({
  el: "#app",
  data: () => {
    return {
      persons: {
        "2": "Person1",
        "3": "Person2",
        "4": "Person3"
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <select id="persons">
    <option v-for="(name, id) in persons" :value="id">{{name}}</option>
  </select>
</div>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement