vue.js - Vue watcher triggered on creating sibling property
问题描述
I'm experiencing problems with vue watchers.
How to explain such behavior: watcher on test.a
is triggered on creating test.b
property?
vm = new Vue({
data: {
test: { a: {}, c: {} }
}
})
vm.$watch('test.a', () => {console.log('> test.a changed')})
vm.$watch('test.b', () => {console.log('> test.b changed')})
vm.$watch(() => vm.test.c, () => {console.log('> test.c changed')}, {deep: true})
setTimeout(() => {
console.log('creating: test.b')
Vue.set(vm.test, 'b', {})
}, 10)
setTimeout(() => {
console.log('changing: test.b')
vm.test.b = 1
}, 20)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>
EDIT:
In real world I use deep watchers, but such behavior was observed for both: normal and deep watcher types.
Creating new property triggers all sibbling deep watches and in most cases normal watches.
解决方案
Vue.set(vm.test, 'b', {})
这test
只会触发一次更改。
vm = new Vue({
data: {
test: { a: {}, b: {}}
}
})
vm.$watch('test.a', () => {console.log('> test.a changed', vm.test)}, {deep: true})
vm.$watch('test.b', () => {console.log('> test.b changed', vm.test.b)}, {deep: true})
setTimeout(() => {
Vue.set(vm.test, 'b', {name: 1})
}, 1000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
使用deep: true
并且test: {a: {}, b: {}}
应该解决问题
推荐阅读
- javascript - Javascript 显示下一个可能的交货日期
- excel - 运行时错误 1004 VBA,设置一个范围的颜色等于另一个
- python - 使用(对于每个单元格)其他数据帧的平均值创建数据帧
- mongodb - 我的 find() 查询可以包含多个相同的字段吗?
- reactjs - 加载 PDF 文件失败。使用反应-pdf
- firebase - 这个流可能吗?流:FirebaseFirestore.instance.collection(widget.name!).snapshots()
- html - 如何在食谱导航栏中的子菜单文本上完全显示颜色?
- object-detection - 找到信息有限的质心边界框
- java - 是否可以用一个 replaceAll 来编写它?
- c# - 如何以日期格式显示 EditorFor 模型值