javascript - Vue关于Reactivity in Depth,为什么Vue可以这样检测属性添加?
问题描述
我测试一个例子!像这样看。
<el-button type="primary" @click="onAdd">add</el-button>
<div>{{arr[3]}}</div>
<div>{{obj.text}}</div>
<div v-show="obj.text2">{{obj.text2}}</div>
data() {
return {
arr: [1, 2, 3, 4],
obj: {
text: 1
}
};
},
像这样使用时,视图无法更新。
methods: {
onAdd() {
// this.$set(this.arr, 3, 0);
this.arr[3] = 0;
this.obj.text2 = 'text2';
}
},
但是view可以全部更新,不知道为什么view依赖obj可以更新?
methods: {
onAdd() {
this.$set(this.arr, 3, 0);
this.obj.text2 = 'text2';
}
},
解决方案
demo:
let obj = {}
Reflect.defineProperty(obj, 'text', {
get() {
return 'text of obj'
},
set(v) {
console.log('you are changing the text property to ' + v)
},
enumerable: true
})
obj.text = 1;
We can detect the property of object when you want to change it.That is how the demo above and code below works.
this.obj.text2 = 'text2';
However,we can only detect operation like code below partially:
this.arr[3] = 0;
because your code could be :
this.arr[100] = 0;
which is add a new property to the array.So,in this case,we can't and don't have to detect operation like:
this.arr[num] = 0;
because the detection is not complete and so trouble.
推荐阅读
- html - 我如何制作具有多个项目引导程序和 jquery 的垂直轮播滑块
- prisma - 如何使用 Prisma2 一次创建多条记录?
- java - 查询字符串 sql
- r - NBA 四分之一秒剩余秒数转换为比赛剩余秒数
- python - Python数据表(或熊猫):基于两列的数据帧的棘手排序
- java - 带有 SpinnerNumberModel 的 JSpinner:是否验证输入的数字?
- c# - Blazor WebAssembly - 找不到适合类型“JwtSecurityTokenHandler”的构造函数
- c# - C# 帮助在更新前验证表数据
- sharepoint-online - 在流程中使用“发送 Http 操作”更新人员组字段时出错
- node.js - Nodejs:Twitter Image Bot 上的 ENOENT