Vue之this.$set的使用——响应式添加对象属性

this.$set说明

语法

Vue.set( target, propertyName/index, value )

参数

参数 类型 说明
taget Object | Array 需要添加或修改属性的目标对象
propertyName/index string | number 属性名称或索引
value
any 设定的值

用法

向响应式对象中添加一个 property,并确保这个新 property 同样是响应式的,且触发视图更新。它必须用于向响应式对象上添加新 property,因为 Vue 无法探测普通的新增 property (比如  this.myObject.newProperty = 'hi' )

注意对象不能是 Vue 实例,或者 Vue 实例的根数据对象。

为什么要使用this.$set

举一个例子,我们用常规方法直接为对象添加属性。

1 <template >
2     <view class="flex flex-direction bg-white">
3         <view>姓名:{{ student.name }}</view>
4         <view>年龄:{{ student.age }}</view>
5         <button class="cu-btn bg-blue" @click="addProperty">添加年龄属性</button>
6     </view>
7 </template>
 1 export
 2 default {
 3         data() {
 4             return {
 5                 student:
 6                 {
 7                     name:
 8                     '张三',
 9                 }
10             }
11         },
12         methods: {
13             addProperty: function(e) {
14                 this.student.age = 15;
15                 console.log("student=>", this.student);
16             }
17         }
18     }

点击按钮时,我们发现年龄属性:添加了,但没有完全添加。——数据中已经有了“age”属性,但视图层没有显示出来。

 

 

视图层为什么没有添加的属性?

由于受JavaScript的限制,vue.js不能监听对象属性的添加和删除,因为在vue组件初始化的过程中,会调用getter和setter方法,所以该属性必须是存在在data中,视图层才会响应该数据的变化。

如何解决?

解决的其中一种方法,就是使用 $set 。我们将 addProperty 进行修改。

1 addProperty: function(e) {
2     this.$set(this.student, "age", 15) console.log("student=>", this.student);
3 }

结果,无论是数据还是视图层,都符合了我们的预期。

 

参考网址

posted @ 2021-08-20 19:59  陆陆无为而治者  阅读(1904)  评论(0编辑  收藏  举报