Tech note: Using VueJS events together with v-model
Ensuring model synchronization occurs before your event handler is called
I want to use 2-way data binding and an event handler together on a form control.
When my handler is called, my model hasn’t been updated from the DOM.
- It works on Chrome but fails in other browsers.
- It used to work on VueJS 2.1.
Always use a
change event handler in combination with
v-modelon DOM elements to make sure the DOM → model synchronization occurs before your handler is called.
It’s possible to use
v-model and an event handler on the same element. Let’s say for example that you need to take an action when a user clicks a radio button, and in the handler you want to know which radio button he clicked:
What event should you use in that example (for the
v-on:something)? If you opt to use
v-on:click, what will the
clicked() function log? If you try the example in Chrome, it will work correctly, and it will output the value of the radio button that the user clicked. However, if you run it in Firefox, the
console.log() will output the previous value. You can use this Codepen to see the behavior in action:
The results will vary on other browsers as well.
The reason this happens is because:
- When a user taps a radio button, some browsers dispatch the
clickevent first, and then if the value of the radio button has changed, dispatch a
changeevent. However, other browsers dispatch the
changeevent first (if needed) and then the
clickevent (e.g. Edge and Safari).
- To synchronize changes in the DOM to the model, Vue binds to the
changeevent for every browser except Chrome, where it binds to
click(see https://github.com/vuejs/vue/commit/8e854a9ed1b606890b53637f201432174bb7508a). So for those browsers that emit
change,the model value won’t be updated before your
clickhandler is called.
To be safe, use the
change event to make sure that your model is updated before your event handler gets called.
Original issue in github: https://github.com/vuejs/vue/issues/4521
About the author
Andre Asselin is a Senior Digital Architect at PointSource, and specializes in building enterprise mobile and desktop web apps.