Categories
Vue Answers

How to Watch Checkbox Clicks in Vue.js?

Spread the love

Sometimes, we want to watch for checkbox clicks in Vue.js.

In this article, we’ll look at how to watch for checkbox clicks in Vue.js.

Watch Checkbox Clicks in Vue.js

To watch for checkbox clicks in Vue.js, we can listen to the change event.

For instance, we can write:

<template>  
  <div id="app">  
    <input type="checkbox" v-model="selected" @change="check($event)" />  
  </div>  
</template>  
<script>  
export default {  
  name: "App",  
  data() {  
    return {  
      selected: true,  
    };  
  },  
  methods: {  
    check(e) {  
      console.log(e.target.checked, this.selected);  
    },  
  },  
};  
</script>

to add the @change directive to the checkbox input to listen to the change event.

Then we can get the checked value of the checkbox with e.target.checked or the this.selected reactive property.

We can use this.selected since we bind the checked value of the checkbox to the this.selected reactive property with the v-model directive.

Conclusion

To watch for checkbox clicks in Vue.js, we can listen to the change event.

By John Au-Yeung

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

Leave a Reply

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