Vue: Different model value in @click handler in different browsers for checkbox element

Created on 28 Sep 2017  ·  4Comments  ·  Source: vuejs/vue

Version

2.4.4

Reproduction link

https://jsfiddle.net/yjmj3oLr/1/

Steps to reproduce

Click checkbox and see console output. It looks like chrome will update model value before click event handler called, while FF call event handler before model will get new value. Both browsers have latest versions.

What is expected?

Expected to get correct model value inside checkbox click event handler.

What is actually happening?

Chrome getting correct model value.
FF getting reversed value.


It seems @change event handler doesn't have those issues like with @click

Most helpful comment

v-model listens to the input event, and different browsers fire click and input in different orders. This is unfixable in Vue because it is just how different browser behaviors. As suggested, instead of using a click listener, use a watcher instead because what you care about is the state, not the click event.

All 4 comments

Why not simply watch the checked value?
https://jsfiddle.net/9nqrfeu0/

Both Firefox & Chrome handle clicks on checkboxes differently. The only way to be sure is to either $watch your checked value as @KKSzymanowski pointed out, or listen to the @change event. Vue has internal logic to ensure that the model is up-to-date before userland event handlers fire, but only if those handlers are attached to the correct events; in this case, @change.

EDIT: Some interesting reading here around your issue: events.js

v-model listens to the input event, and different browsers fire click and input in different orders. This is unfixable in Vue because it is just how different browser behaviors. As suggested, instead of using a click listener, use a watcher instead because what you care about is the state, not the click event.

The above recommendation indeed solves the browser-compatibility issue. However when you are looping through an array and creating a list of checkboxes, you are adding a watcher to every checkbox. This is also fine (minus the performance hit), but when you want to do something to all of those checkboxes, say "Clear All", then the watch is going to fire multiple events based on all of the values changing.

Was this page helpful?
0 / 5 - 0 ratings