Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue Dirty state trigering in component

Tags:

vue.js

vuejs2

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()">

like image 574
Sanne V Avatar asked Feb 02 '18 09:02

Sanne V


3 Answers

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>
like image 116
dfsq Avatar answered Dec 16 '22 10:12

dfsq


I am not that experienced in Vue but watch seems preferable here.

 watch: {
 item: {
    handler(val){
      // do stuff
    },
    deep: true
  }
}
like image 33
Menelaos Vergis Avatar answered Dec 16 '22 11:12

Menelaos Vergis


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()
}
...
like image 29
lokanath Avatar answered Dec 16 '22 10:12

lokanath