Javascript 监视深度对象更改时不会触发VueJS监视程序
我得到了一个代码沙盒,它复制了我的问题: 我正在处理一个依赖于对象的组件,该对象具有可以动态添加到该对象的数据,因此,例如,在一个单独的Javascript 监视深度对象更改时不会触发VueJS监视程序,javascript,node.js,vue.js,vuejs2,vuejs3,Javascript,Node.js,Vue.js,Vuejs2,Vuejs3,我得到了一个代码沙盒,它复制了我的问题: 我正在处理一个依赖于对象的组件,该对象具有可以动态添加到该对象的数据,因此,例如,在一个单独的.js文件中,我导出以下对象: export default { defaultSection1: { displayName: 'Action', }, defaultSection2: { displayName: 'Thriller', }, } 我在组件中导入此对象 我从Lodash获得了一个去抖动器设置,这样当数据发生
.js
文件中,我导出以下对象:
export default {
defaultSection1: {
displayName: 'Action',
},
defaultSection2: {
displayName: 'Thriller',
},
}
我在组件中导入此对象
我从Lodash获得了一个去抖动器设置,这样当数据发生变化时,它只会在两秒钟后触发一次观察者。观察者被触发对于对象中已经存在的数据来说非常好(在我的示例中键入输入文本框,观察者被触发)。但是,当我向对象动态添加数据时,观察者根本不会被触发。只有在来回更改路由时,数据才会更新,但不会触发观察者。为什么会这样?当数据被动态添加到对象时,我可以做些什么来触发观察程序
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,
},
},
当数据明显改变时,为什么不触发观察者
另一件我注意到的非常奇怪的事情是,在VUE3.0
中,监视程序被触发时使用的代码与完全相同
.在vue 2中,更新数组中的项目或对象中的嵌套字段时存在反应性问题,要解决此问题,必须使用
此。$set()
方法:
this.$set(this.data,newSectionId, {displayName: 'Custom'})
这个问题在Vue 3中得到了解决。你可以这样做:
const newSectionId = Math.floor(Math.random() * 1000);
this.data[newSectionId] = {
displayName: 'Custom'
}