【问题标题】:Vue js watcher does not react to changesVue js watcher 对更改没有反应
【发布时间】:2020-08-30 12:24:42
【问题描述】:

我看到了一些关于 vue.js 观察者的问题,但是我没有找到处理我的问题的问题,所以这里是:

在我的 SomeComponent.vue 中,我使用以下代码:

...
props: ['value']
,
watch: {
    value(val) {
        console.log(val);
    }
},

在我的父 vue 页面中,使用这个组件我使用这个,它正在工作:

<template>
    <div>
        <SomeComponent
            v-model="test"
        ></SomeComponent>
    </div>
</template>
data() {
    return {
        test: {}
    };
},
created() {
    this.test = this.DoSomething();
},

如果我添加另一个属性,则不再触发观察者:

<template>
    <div>
        <SomeComponent
            v-model="test"
        ></SomeComponent>
    </div>
</template>
data() {
    return {
        test: {}
    };
},
created() {
    this.test.Prop1 = this.DoSomething();
    this.test.Prop2 = "Test";
},

编辑: 在 Behappy 的回答之后,我的组件部分现在看起来像这样:

...
props: ["value"],
watch: {
    value: {
        handler(val) {
            console.log(val);
        },
        deep: true
    }
},

【问题讨论】:

    标签: javascript vue.js vue-component


    【解决方案1】:

    这是因为您的propObject

    要深入观看,您可以这样做:

    watch: {
        value: {
            handler(val) {
              console.log(val);
            },
            deep: true
        }
    },
    

    created DOM 还没有渲染。所以你发送给子组件的道具还没有更新。refer link

    和其他答案一样,更改对象的正确方法是使用this.$set

      mounted() {
        this.$set(this.test, 'Prop1', this.DoSomething())
        this.$set(this.test, 'Prop2', 'Test')
      },
    

    【讨论】:

    • 欢迎您。我认为更改created 不会触发watch,因为在发送到子组件之前值会发生变化。
    【解决方案2】:

    docs中提到的:

    由于 JavaScript 的限制,Vue 无法检测到某些类型的更改。但是,有一些方法可以绕过它们以保持反应性。

    对象

    Vue 无法检测属性添加或删除。由于 Vue 在实例初始化期间执行 getter/setter 转换过程,因此必须在 data 对象中存在一个属性,以便 Vue 对其进行转换并使其具有响应性。例如:

    var vm = new Vue({
      data: {
        a: 1
      }
    })
    // `vm.a` is now reactive
    
    vm.b = 2
    // `vm.b` is NOT reactive
    

    Vue 不允许动态地将新的根级反应属性添加到已创建的实例中。但是,可以使用 this.$set(object, propertyName, value) 方法向嵌套对象添加反应属性:

    你的情况是:

    created() {
        this.$set(this.test, 'Prop1', this.DoSomething())
        this.$set(this.test, 'Prop2', "Test")
    },
    

    或者,您也可以为现有对象分配多个属性,例如,使用Object.assign() 像:

    this.test = Object.assign({}, this.test, { 'Prop1': 1, 'Prop2': 2 })
    

    【讨论】:

      猜你喜欢
      • 2021-08-14
      • 1970-01-01
      • 2018-10-11
      • 2018-12-23
      • 1970-01-01
      • 2019-05-16
      • 2021-05-09
      • 2018-06-13
      • 2013-05-14
      相关资源
      最近更新 更多