【发布时间】:2021-01-28 10:12:54
【问题描述】:
我有一个可以重现我的问题的代码框:codesandbox example watcher not triggering。
我正在开发一个依赖于对象的组件,该对象的数据可以动态添加到对象中,例如,在单独的.js 文件中,我正在导出以下对象:
export default {
defaultSection1: {
displayName: 'Action',
},
defaultSection2: {
displayName: 'Thriller',
},
}
我在我的组件中导入这个对象。
我从 Lodash 获得了一个 debouncer 设置,这样当数据发生变化时,它只会在两秒后触发一次 watcher。对于已经在对象中的数据,观察者触发非常好(在我的示例中输入输入文本框,观察者被触发)。但是当我向对象动态添加数据时,观察者根本不会触发。只有当我来回更改路线时,数据才会更新,但不会触发观察者。为什么是这样?当数据被动态添加到对象时,我该怎么做才能触发观察者。
methods: {
fetchAndUpdateData(){
console.log('Fetching data...')
},
addCustomSection(){
//The watcher should be triggered when this function is called
const newSectionId = Math.floor(Math.random() * 1000);
this.data[newSectionId] = {
displayName: 'Custom'
}
}
},
computed: {
dataWatcher() {
return this.data;
},
updateData() {
return debounce(this.fetchAndUpdateData, 2000);
},
},
watch: {
dataWatcher: {
handler() {
console.log('Watcher triggered')
this.updateData();
},
deep: true,
},
},
为什么观察者没有被触发,而数据显然正在改变?
我注意到的另一件很奇怪的事情是,在Vue 3.0 中,观察者被完全相同的代码触发。
Codesandbox in Vue 2.6.11, watcher not triggering.
Codesandbox in Vue 3.0, watcher IS triggered with exactly the same code.
【问题讨论】:
标签: javascript node.js vue.js vuejs2 vuejs3