this.$set实现什么功能,为什么要用它?
当我们给对象加了一个属性,在控制台能打印出来,但是却没有更新到视图上时,也许这个时候就需要用到
调用方法:this.$set( target, key, value )
target:要更改的数据源(可以是对象或者数组)
key:要更改的具体数据
value :重新赋的值
<template>
<div>
<h2>{{ obj }}</h2>
<h2>{{ arr }}</h2>
</div>
</template>
<script>
export default {
data() {
return {
obj: {
a: "Hello World!",
},
arr: [1, 2, 3],
};
},
mounted() {
this.changeObj();
this.changeArr();
},
methods: {
changeObj() {
// this.obj.b = "新增的属性b";
this.$set(this.obj, "b", "新增的属性b");
console.log(this.obj);
},
changeArr() {
// this.arr[4] = 7;
// this.arr.length = 5;
this.$set(this.arr, "3", 7);
console.log(this.arr);
},
},
};
</script>