vue中较为重要的一个知识点
//如果说引用数据类型没定义该属性,属性改变的时候视图不更新
//该如何解决?
//1. $set方法 (强制性更新视图)
//语法:
//this. $set (目标对象 / 数组, 属性 / 下标, 新值) ;
<template>
<div class="about">
<h1>{{ obj }}</h1>
<h1>{{ arr }}</h1>
<h1>{{ arr1 }}</h1>
<button @click="change">更新</button>
</div>
</template>
<script>
export default {
data() {
return {
obj: {},
arr: [],
arr1: [{}, {}],
};
},
methods: {
change() {
this.$set(this.obj, "name", "张三");
this.$set(this.arr, 0, 1);
this.$set(this.arr1, 0, { name: "张三" });
this.$set(this.arr1[1], "name", "李四");
},
},
};
</script>
2. JSON.parse(JSON.stringify( ) )
<template>
<div class="about">
<p>{{ obj }}</p>
<h1>{{ arr }}</h1>
<h2>{{ arr1 }}</h2>
<button @click="change">更新</button>
</div>
</template>
<script>
export default {
data() {
return {
obj: {},
arr: [],
arr1: [{}, {}],
};
},
methods: {
change() {
this.obj.name = "张三";
this.obj = JSON.parse(JSON.stringify(this.obj));
this.arr[0] = 1;
this.arr = JSON.parse(JSON.stringify(this.arr));
this.arr1[0] = { name: "张三" };
this.arr1 = JSON.parse(JSON.stringify(this.arr1));
},
},
};
</script>