Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

vue.js - How to reactively monitor if Vue JS data object has changed?

In a Vue JS project, i have the following pretty standard pattern:

data () {
  model: {
    id: uid(),
    label: null,
    options: []
    .... etc.
  }
}

The model property feeds a form and I need to show an alert when the data model is 'dirty' - any key may have been changed by the user since last saving.

The problem is - the data may be affected many different methods - v-model for inputs, custom events from child components like selects and toggle switches etc and the options array maybe edited by drag-and-drop sorting, adding/removing elements, etc.

I'm looking for - ideally - a single REACTIVE (eg computed) property I can watch to know if the model is dirty so I can prompt the user to save.

Does Vue have a hidden or undocumented property/method, something like $vm._isDirty? I know I can use a compare fn to handle it manually, but it's not reactive, and I know I could use a deep watcher on the model, but that's computationally expensive and some of these models are pretty big.

What approach have other developers have used?

question from:https://stackoverflow.com/questions/65941584/how-to-reactively-monitor-if-vue-js-data-object-has-changed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can simply use a deep watcher:

watch:
{
  model:
  {
    deep: true,
    handler(newValue, oldValue)
    {
      this.modified = true; // or whatever you need to do when the model becomes dirty
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...