Vue.js正在观看深层物业 [英] Vue.js watching deep properties

查看:85
本文介绍了Vue.js正在观看深层物业的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 vue.js 对象上观看属性,但我没有得到我想要的结果,我的代码如下:

I'm trying to watch properties on a vue.js object, but i'm not getting the result that i want, my code is the following:

var vueTable = new Vue({
    el: '#vue-table',
    data: {
        filters: {},
    },
    watch: {
        filters: {
            handler: function () {
                console.log('watched');
            },
            deep: true
        }
    }
}

我在输入上有一个 v-model

<input class="form-control" v-model="filters.name">

现在当页面加载时,它只在控制台中记录监视一次,每当我更改输入时它都不会记录任何内容。

Now when the page loads it logs watched in the console just once, whenever i change the input it doesn't log anything.

然而,当我在表格初始化后放入 vueTable.filters = {name:'something'}; 时,它会触发每一个改变。

Yet when i put vueTable.filters = {name: 'something'}; after the table initalization it will trigger on every change.

这是出乎意料的行为吗?或者我们是否必须定义所有属性以便观察它们?

Is this unexpected behaviour? or do we have to define all our properties in order for them to be watched?

推荐答案

文档涵盖了这个此处


由于现代JavaScript的限制(以及放弃
Object.observe),Vue无法检测属性添加或删除。

Due to the limitations of modern JavaScript (and the abandonment of Object.observe), Vue cannot detect property addition or deletion.

从空对象开始并将 v-model 设置为 filters.name ,您最终动态添加属性。在这种情况下,最好的方法是初始化数据中的属性。它没有值。

By starting with an empty object and setting v-model to filters.name, you end up adding a property dynamically. The best approach in this case would be to initialize the property in the data. It doesn't have to have a value.

data: {
    filters: { name: null },
}

这篇关于Vue.js正在观看深层物业的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆