Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue selected prop not working with v-model

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

like image 483
Saeed Vaziry Avatar asked Oct 16 '17 13:10

Saeed Vaziry


People also ask

Can we use props in V-model?

In 2.2 we introduced the model component option that allows the component to customize the prop and event to use for v-model . However, this still only allowed a single v-model to be used on the component.

How do I get selected value at Vue?

We can get the selected option on change with Vue. js by setting @change to a method. We set v-model to the key reactive property bind the selected value attribute value to key . And we set @change to onChange($event) to call onChange with the change event object.

How do I call Vue props?

To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.


Video Answer


2 Answers

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

like image 96
hannes neukermans Avatar answered Oct 28 '22 05:10

hannes neukermans


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
like image 1
Armand Avatar answered Oct 28 '22 03:10

Armand