In this tutorial, you will learn how to set the default value of a select combo box in VueJS. We are going to populate a dataset of a dropdown select by creating an array of objects. In this example, we going to populate a fruit object contains the property of an Id and Name.
Here is the full source code in HTML.
<!doctype html>
<html>
<head>
<title>bytutorial.com Demo - Set dropdown selected value</title>
</head>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<body>
<div id="app">
<p>Select your favourite fruit.</p>
<select v-model="selectedValue">
<option v-for="fruit in fruitArray" v-bind:key="fruit.Id" v-bind:value="fruit.Id">{{ fruit.Name }}</option>
</select>
</div>
</body>
<script>
var app = new Vue({
el: '#app',
data: {
selectedValue: "",
fruitArray: []
},
mounted(){
this.fruitArray.push({'Id': '', 'Name': 'Select Fruit'});
this.fruitArray.push({'Id': '1', 'Name': 'Apple'});
this.fruitArray.push({'Id': '2', 'Name': 'Banana'});
this.fruitArray.push({'Id': '3', 'Name': 'Mango'});
this.fruitArray.push({'Id': '4', 'Name': 'Orange'});
this.fruitArray.push({'Id': '5', 'Name': 'Watermelon'});
this.selectedValue = "3"
}
});
</script>
</html>
If you have a look above code. In the data section. We declare two variables. The first one is called 'selectedValue'. This variable will be used to hold the value of the selected combo box option. In this example, it will be the Id of the fruit object which will be a number string.
The second variable will be an array object used to hold the list of fruit object. We initiate the default list value in 'mounted' section. We also define the default value of selected option in this section into 'selectedValue' variable. For example: we set to 3 which means by default it will set to 'Mango'.
See below result screenshot.
Demo
To see the live demo, you can click the following link.
See the example of setting a default value for a select combo box in action.
Download
To download the demo file. Please click the following URL link.