admin管理员组

文章数量:1180542

The :selected prop is not selecting the target option in Vue2 when i use v-model for select :

Template

...
<select v-model="form.item">
    <option :value="item.id" v-for="(item, index) in items" :selected="item.status == 2">{{ item.name }}</option>
</select>
...

Script

data: function () {
    return {
        items: [{id:1, name: "foo", status: 1},{id: 3, name: "bar", status: 2}],
        form: {item: null}
    }
}

In this case , after mounted there is no selected option.

How can i fix this?

Note

When i remove v-model it works fine (target option is selected by default) but i don't have the value of the selected option in form.item

The :selected prop is not selecting the target option in Vue2 when i use v-model for select :

Template

...
<select v-model="form.item">
    <option :value="item.id" v-for="(item, index) in items" :selected="item.status == 2">{{ item.name }}</option>
</select>
...

Script

data: function () {
    return {
        items: [{id:1, name: "foo", status: 1},{id: 3, name: "bar", status: 2}],
        form: {item: null}
    }
}

In this case , after mounted there is no selected option.

How can i fix this?

Note

When i remove v-model it works fine (target option is selected by default) but i don't have the value of the selected option in form.item

Share Improve this question edited Oct 16, 2017 at 14:04 Saeed Vaziry asked Oct 16, 2017 at 13:54 Saeed VazirySaeed Vaziry 2,3557 gold badges28 silver badges41 bronze badges 2
  • 1 v-model and :selected don't work together. It is explained in the official doc. You can only use one of both. – hannes neukermans Commented Oct 16, 2017 at 14:06
  • @hannesneukermans do you know any good solution for this? – Saeed Vaziry Commented Oct 16, 2017 at 14:16
Add a comment  | 

3 Answers 3

Reset to default 27

v-model will ignore the initial value, checked or selected attributes. found on any form elements

The solution is to remove :selected binding. and use data props to bind to v-model

<select v-model="form.selectedItem">
   <option :value="item.id" v-for="(item, index) in items">{{ item.name }}
   </option>
</select>

declare vue instance as

data() {
 return {
  selectedItem: 2
 }
}

link to official documentation

Another solution is by using $refs instead of v-model.

<select ref="selectedItem">
   <option v-for="(item, index) in items" :value="item.id" :selected="item.status == 2">
      {{ item.name }}
   </option>
</select>

Then to get the value of the selected item, call...

this.$refs.selectedItem.value
<select v-model="selectedGroup">
    <option :value="false" :selected="selectedGroup == false">All</option>
    <option v-if="organization.groups" v-for="group in organization.groups" :value="group">{{ group }}</option>
</select>

本文标签: javascriptVue selected prop not working with vmodelStack Overflow