You were on the right track using v-model
and selectedFlavor
on the select. Doing so binds the value of the select box to the value of selectedFlavor
. When you change the value of selectedFlavor
you change the value of the select element. This works both ways; ie. if you change the select box you'll also change the value of selectedFlavor
(ie two-way data binding, reactivity).
Changing the value of the select element also changes which option element has the selected
attribute. You can use this v-model data binding to achieve your goal, but this is only a functionally equivalent result. Your use case may differ.
If you can change the value of the select box using this method then setting the initial value of selectedFlavor
in the data
object will achieve your goal of setting a default value of the select box and therefore which option element has the selected attribute.
You can change the value of the select box by changing the value of the data model you bind to either directly or (preferably) through some sort of state management like Vuex. State management answers your larger question around managing the state of the select based on dynamic data from other events, data sources, API's, web sockets, etc...
I'm directly modifying the value of selectedFlavor
below only to highlight the basic concept, but I also tried to hint at what this might look like within a state management paradigm.
<select v-model="selectedFlavor">
<option v-for="flavor in flavors"
:value="flavor"
@change="onChangeFlavour"
>{{ flavor }}</option>
</select>
new Vue({
el: '#app',
data() {
return {
selectedFlavor: 'lime', // Default value is set here
flavors: ['blueberry', 'lime', 'strawberry']
}
},
methods: {
onChangeFlavour(event) {
// do what you want with the new value when the select box is changed
console.log(event.srcElement.value);
// OR preferably
console.log(this.selectedFlavor); // because binding
},
setFlavour(newFlavour){
// change the value
this.selectedFlavor = newFlavour;
}
}
});