Sometimes, we want to fire an event when the v-model
value changes with Vue and JavaScript.
In this article, we’ll look at how to fire an event when the v-model
value changes with Vue and JavaScript
Fire an Event When the v-model Value Changes with Vue and JavaScript
We can listen to the change event to do something when the v-model
value changes value.
For instance, we can write:
<template>
<div id="app">
<input
type="radio"
name="fruit"
value="apple"
v-model="fruit"
@change="onChange"
/>
apple
<input
type="radio"
name="fruit"
value="orange"
v-model="fruit"
@change="onChange"
/>
orange
<input
type="radio"
name="fruit"
value="grape"
v-model="fruit"
@change="onChange"
/>
grape
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
fruit: "apple",
};
},
methods: {
onChange() {
console.log(this.fruit);
},
},
};
</script>
We have 3 radio buttons bound to the fruit
reactive property with v-model
.
In each radio button, we have the @change
directive set to the onChange
method.
In onChange
, we get the this.fruit
value.
Now when we click on a radio button, the current this.fruit
value should be logged.
It should be one of the value
attribute value of each radio button.
Conclusion
We can listen to the change event to do something when the v-model
value changes value.