Vue "on-change" method not working with checkbox

Viewed 2878

I am trying to use a method with a checkbox and it's not firing in VueJS. I have included snippets from the template section and methods section of my component. The component and everything else in it load just fine without any console errors, but I can't get this method to fire when I click the checkbox. What am I doing wrong?

FROM template:

<input type="checkbox" v-on:change="myMethod(this)" />

FROM methods:

myMethod: function (chck) {
                        if (chck.checked == true) {
                            console.log("true");
                        } else if (chck.checked == false) {
                            console.log("false");
                        }
                },
1 Answers

Passing this to an event handler in Vue will pass the entire component into the event listener, instead of just the element. This is because, inside of vue-bindings, you're just writing JavaScript within the scope of the component.

Instead, don't pass anything in your template (which will result in your method being passed the regular event object), and use event.target.checked to check if the checkbox was checked (actually, don't do it exactly this way, this is just a more "direct" solution. See below for the proper way to do it).

new Vue({
  el: '#app',
  methods: {
    myMethod: function(event) {
      if (event.target.checked) console.log("checked");
      else console.log("unchecked");
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input type="checkbox" @change="myMethod" />
</div>

However, it's worth noting that the proper way to do this is with v-model. That way, you maintain a single source of truth, and your app remains data-driven:

new Vue({
  el: '#app',
  data: {
    tickBoxChecked: false,
  },
  methods: {
    myMethod: function() {
      if (this.tickBoxChecked) console.log("checked");
      else console.log("unchecked");
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input type="checkbox" v-model="tickBoxChecked" @change="myMethod" />
</div>

Related