vue js how to set option value selected
With vue 2, the provided answer won't work that well. I had the same problem and the vue documentation isn't that clear concerning <select>
. The only way I found for <select>
tags to work properly, was this (when talking of the question):
<select v-model="formVariables.country_id">
<option v-for = "country in countrylist" :value="country.id" >{{country.name}}</option>
</select>
I assume, that the @-sign in @{{...}}
was due to blade, it should not be necessary when not using blade.
In VueJS 2 you can bind selected
to the default value you want. For example:
<select
class="breadcrumb_mountain_property"
id="country_id"
v-model="formVariables.country_id"
v-on:change="getMountain(formVariables.country_id);">
<option
v-for = "country in countrylist"
:selected="country.id == 1"
:value="country.id" >
{{country.name}}
</option>
</select>
So, during the iteration of the countryList, the country with the id 1 will be selected because country.id == 1
will be true
which means selected="true"
.
UPDATED:
As Mikee suggested, instead of v-on="change:getMountain(formVariables.country_id);"
there is a new way to for binding events. There is also a short form @change="getMountain(formVariables.country_id);"
You should use the 'options
' attribute in place of trying to v-repeat <option></option>
:
VM
data: {
countryList: [
{ text:'United States',value:'US' },
{ text:'Canada',value:'CA' }
]
},
watch: {
'formVariables.country_id': function() {
// do any number of things on 'change'
}
}
HTML
<select
class="breadcrumb_mountain_property"
id="country_id"
v-model="formVariables.country_id"
options="countryList">
</select>