Categories
Vue Answers

How to Fire an Event When the v-model Value Changes?

Spread the love

Sometimes, we want to fire an event when the v-model value changes.

In this article, we’ll look at how to fire an event when the v-model value changes

Fire an Event When the v-model Value Changes

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to Fire an Event When the v-model Value Changes?”

Note that this only shows v-model changes resulting from a user action on the input. If it changes from something external, the function will not fire.

Leave a Reply

Your email address will not be published. Required fields are marked *