最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pass array of object to select options in Vue 2.0 - Stack Overflow

programmeradmin1浏览0评论

I have a select which I want to populate from the array of objects like

[{"id": 1, "name": "Some name"},
 ... 
{"id": 5, "name": "Another name"}]

which is stored in items in data property of the Vue

var app = new Vue({
el: "#app",
data: {
    items: [],
....

    }
})

I'm trying to do it like with the v-for and v-model like that:

  <select id="categories" v-model="items">
      <option v-for="item in items" :value="item.id">{{ item.name }}</option>
  </select>

and it doesn't work, however if I tried the same code with the int Array everything is fine. Can't wrap my head around it.

I have a select which I want to populate from the array of objects like

[{"id": 1, "name": "Some name"},
 ... 
{"id": 5, "name": "Another name"}]

which is stored in items in data property of the Vue

var app = new Vue({
el: "#app",
data: {
    items: [],
....

    }
})

I'm trying to do it like with the v-for and v-model like that:

  <select id="categories" v-model="items">
      <option v-for="item in items" :value="item.id">{{ item.name }}</option>
  </select>

and it doesn't work, however if I tried the same code with the int Array everything is fine. Can't wrap my head around it.

Share Improve this question asked Jun 16, 2017 at 15:13 virtual98virtual98 791 gold badge3 silver badges12 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

Use v-model for the selected value

<select id="categories" v-model="selectedValue">
  <option v-for="item in items" :value="item.id">{{ item.name }}</option>
</select>

Add selectedValue to your data.

var app = new Vue({
  el: "#app",
  data: {
    items: [],
    selectedValue: null

  }
})

const items = [{"id": 1, "name": "Some name"},
{"id": 5, "name": "Another name"}]

var app = new Vue({
el: "#app",
data: {
    items,
    selectedValue: null
    }
})
<script src="https://unpkg./[email protected]/dist/vue.js"></script>
<div id="app">
  <select id="categories" v-model="selectedValue">
      <option v-for="item in items" :value="item.id">{{ item.name }}</option>
  </select>
  
  Selected Value: {{selectedValue}}
</div>

发布评论

评论列表(0)

  1. 暂无评论