How to Use @change in Vue with select Tags
Mar 25, 2021
If you want to avoid having to use v-model
with your <select>
tags,
you can use Vue's v-on:change
directive, or just the shorthand @change
.
In every option
tag, you must set the value
property to define the value of each option.
Vue event handlers have a special $event
property that describes the event, and $event.target.value
contains the value of the newly selected option.
From there, @change
can handle the rest. Below is a live example:
Below is the code:
Vue.createApp({
data: () => ({ selected: '' }),
methods: {
switchSelect(event) {
this.selected = event.target.value;
}
},
template: `
<div>
<p>Your choice is: {{selected}}</p>
<select @change="switchSelect($event)">
<option value="">Choose</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</div>
`
});
Vue School has some of our favorite Vue
video courses. Their Vue.js Master Class walks you through building a real
world application, and does a great job of teaching you how to integrate Vue
with Firebase.
Check it out!
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!