[Vuejs]-When clicking on checkbox it shows false

2👍

Because the Console Logs it before the actual change happened, for example if you change the console.log() into an alert() you can clearly see the timing order and which action is performed first.

Edit: You could set a watcher on the checked so whenever the value actually changed you perform an action

watch: {
    checked: function (val) {
       console.log(val)
    },

3👍

There is indeed a delay in the execution as Badgy mentioned above. The issue is that you try to combine v-model and @click. In this case I would suggest to write a custom version of v-model that gives you more control.

In reality, <input v-model="checked" /> is just a simpler form of <input :value="checked" @input="checked= $event.target.value"> Therefore, you can do this

<input type="checkbox" id="checkbox" :value="checked" @click='toggle'>

And toggle the value like this

toggle: function(){
  this.checked = !this.checked;
}

Here is the jsfiddle of the result https://jsfiddle.net/dan_elision/7fx1kocp/. The advantage of this approach is that you have more control and you do not need to use watchers, which is a good habit to save only for expensive operations (see documentation).

👤Dan

Leave a comment