0
点赞
收藏
分享

微信扫一扫

Vue.set()和vm.$set()方法及不足

爱上流星雨 2022-03-20 阅读 35

什么时候要使用?

官方文档解释:

var vm = new Vue({
  data:{
    a:1
  }
})

// `vm.a` 是响应式的

vm.b = 2
// `vm.b` 是非响应式的
Vue.set(vm.someObject, 'b', 2)
this.$set(this.someObject,'b',2)

以上。
在data中的数据,Vue底层会存在一个递归函数,检测所有是对象的数据,逐一添加setter和getter。
我们新定义的,未在data中出现过的数据,在转化为虚拟DOM时,不会经历为其添加setter和getter的过程,而这正是响应式的关键。

使用方法

Vue.set( target , key , value )

vm.$set( target ,key , value )

eg:向data中的student对象中添加一个性别属性:

Vue.set(this.student , 'sex' , '男')

this.$set(this.student , 'sex' , '男')

方法缺陷

先上总结:
此方法只允许给data里的某一个对象追加属性,不允许给data追加属性
即:vm,vm的根数据对象都不允许作为target

eg:

Vue.set(vm._data , "hobby" , "soccer")

错误信息:
[Vue warn]: Avoid adding reactive properties to a Vue instance or its root $data at runtime

举报

相关推荐

0 条评论