Javascript Vue Watch 未触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46666819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:32:28  来源:igfitidea点击:

Vue Watch not triggering

javascriptnode.jsvue.jsvuejs2

提问by Sérgio Reis

Trying to use vue watch methods but it doesn't seem to trigger for some objects even with deep:true.

尝试使用 vue watch 方法,但即使使用deep:true.

In my component, I recieve an array as a prop that are the fields to create the following forms. I can build the forms and dynamicly bind them to an object called crudModelCreateand everything works fine (i see in vue dev tools and even submiting the form works according to plan)

在我的组件中,我收到一个数组作为 prop,它是创建以下表单的字段。我可以构建表单并将它们动态绑定到一个名为的对象crudModelCreate,一切正常(我在 vue 开发工具中看到,甚至按计划提交表单工作)

But I have a problem trying to watch the changes in that dynamic object.

但是我在尝试观察该动态对象中的变化时遇到了问题。

  <md-input v-for="(field, rowIndex) in fields" :key="field.id" v-model="crudModelCreate[field.name]" maxlength="250"></md-input>

   ...

   data() {
      return {
         state: 1, // This gets changed somewhere in the middle and changes fine
         crudModelCreate: {},
      }
   },
   ...
   watch: {
        'state': {
            handler: function(val, oldVal) {
                this.$emit("changedState", this.state);
                // this works fine
            },
        },
        'crudModelCreate': {
            handler: function(val, oldVal) {
                console.log("beep1")
                this.$emit("updatedCreate", this.crudModelCreate);
                // This doesn't work
            },
            deep: true,
            immediate: true
        },
    }

采纳答案by ricardoorellana

From the docs

从文档

Due to the limitations of modern JavaScript (and the abandonment of Object.observe), Vue cannot detect property addition or deletion. Since Vue performs the getter/setter conversion process during instance initialization, a property must be present in the data object in order for Vue to convert it and make it reactive.

由于现代 JavaScript 的限制(以及 Object.observe 的放弃),Vue 无法检测属性添加或删除。由于 Vue 在实例初始化期间执行 getter/setter 转换过程,因此数据对象中必须存在一个属性,以便 Vue 转换它并使其具有反应性。

Please take a look to Reactivity in Depth https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

请深入了解反应性https://vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats