Raaz
Raaz

Reputation: 1771

when clicking on checkbox it shows false

<div id="app">
  <h2>Todos:</h2>
 <input type="checkbox" id="checkbox" v-model="checked" @click='toggle'>
 {{checked}}
</div>

new Vue({
  el: "#app",
  data: {
    checked: false,
  },
  methods: {
    toggle: function(){
    console.log(this.checked);
    }
  }
})

When clicking a checkbox the console value is shown as false but in the view it is printed as true. Why is it tha the value are different in console and the view?

here is a link to the fiddle. Please check console value and view value

Upvotes: 0

Views: 1694

Answers (2)

Dan
Dan

Reputation: 493

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).

Upvotes: 3

niclas_4
niclas_4

Reputation: 3674

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)
    },

Upvotes: 2

Related Questions