Sometimes, we want to get the selected option on change with Vue.js.
In this article, we’ll look at how to get the selected option on change with Vue.js.
Get the Selected Option on Change with Vue.js
We can get the selected option on change with Vue.js by setting @change
to a method.
For instance, we can write:
<template>
<div id="app">
<select name="fruit" @change="onChange($event)" v-model="key">
<option value="1">apple</option>
<option value="2">orange</option>
</select>
</div>
</template>
<script>
export default {
name: "App",
data() {
return { key: "" };
},
methods: {
onChange(event) {
console.log(event.target.value, this.key);
},
},
};
</script>
We set v-model
to the key
reactive property bind the selected value
attribute value to key
.
And we set @change
to onChange($event)
to call onChange
with the change event object.
In onChange
, we get the event
object, and get the selected value
attribute value with event.target.value
.
And we get the same value with this.key
since we bound it to the selected value
attribute value with v-model
.
Alternative, we can remove ($event)
and write:
<template>
<div id="app">
<select name="fruit" @change="onChange" v-model="key">
<option value="1">apple</option>
<option value="2">orange</option>
</select>
</div>
</template>
<script>
export default {
name: "App",
data() {
return { key: "" };
},
methods: {
onChange(event) {
console.log(event.target.value, this.key);
},
},
};
</script>
to get the same result.
Conclusion
We can get the selected option on change with Vue.js by setting @change
to a method.