Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

javascript - Populate <select> <option> 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>
question from:https://stackoverflow.com/questions/65617326/populate-select-option-using-v-for-loop-in-vuejs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...