I want to set one of the available <option>
tags to default. On the <select>
tag I am using v-model
and I know that the vue.js
documentation states the following in regard to this:
v-model
will ignore the ...selected
attributes found on any form elements. It will always treat the Vue instance data as the source of truth. You should declare the initial value on the JavaScript side, inside the data option of your component.
So I am using the selected
attribute with v-bind and passing either directly true
to it or through a variable in the data option. Unfortunately it doesn't work. Here is an jsfiddle.
And here is the example code:
HTML
<div id="app">
<select v-model="selectedData" @change="doSomething">
<option :selected="true" value="">
Please select account
</option>
<option
v-for="data in myData"
:key="data.id"
:value="data.val"
>
{{ data.val }}
</option>
</select>
{{ selectedData }}
</div>
JavaScript
new Vue({
el: "#app",
data: {
selected: true,
selectedData: null,
myData: [
{ id: 1, val: "abc" },
{ id: 2, val: "def" },
{ id: 3, val: "ghi" },
{ id: 4, val: "jkl" },
]
},
methods: {
doSomething: function(){
console.log('hello')
}
}
})
The <select>
tag's model is what is actually driving the chosen item in the drop down.
<select v-model="selectedData" @change="doSomething">
Change your "default" option to the following
<option value="-1">
Please select account
</option>
and in your data object, instead of having null
assigned to your selected value on initialization, set it to -1
data: {
selectedData: -1,
myData: [
{ id: 1, val: "abc" },
{ id: 2, val: "def" },
{ id: 3, val: "ghi" },
{ id: 4, val: "jkl" },
]
},