I have a page in Vue with input fields. I wanna show a message when someone changed any input field in that component. I'm used to Angular where you can use the isDirty function, but Vue doesn't have that.
Is there a way to catch all keyup events in a Vue view? So I can catch that and set a variable to true for the message to be shown?
Now I have this added to all input models:
<input v-model="foo" @change="someThingChanged()">
Is there a way to catch all keyup events in a Vue view?
You can bind single onchange
event on the parent container and benefit from the fact that change events bubble:
<div class="container" @change="someThingChanged()">
<input v-model="foo">
<input v-model="bar">
... etc.
</div>
I am not that experienced in Vue but watch seems preferable here.
watch: {
item: {
handler(val){
// do stuff
},
deep: true
}
}
Apart from checking for dirty, We can also use Component Navigation guards to prevent user from navigating elsewhere if the form is dirty. BeforerouteLeave Vue Component route gaurd.
...
data: {
formDirty: false,
}
methods: {
somethingchanged() {
formDirty = true,
}
}
beforeRouteLeave (to, from, next) {
if(formDirty){
const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
if (answer) {
return next()
} else {
return next(false)
}
}
return next()
}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With