首先声明this.$set和Vue.set的原理是相同的;都是使用了set函数。set函数是从 …/observer/index 文件中导出的,区别在于Vue.set()是将set函数绑定在Vue构造函数上,this.$set()
是将set函数绑定在Vue原型上。
在我们使用vue进行开发的过程中,可能会遇到一种情况:当生成vue实例后,当再次给对象赋值时,有时候并不会自动更新到视图上去; 当我们去看vue文档的时候,会发现有这么一句话:如果在实例创建之后添加新的属性到实例上,它不会触发视图更新。
<template> <div class="hello"> <ul v-for="item in arr"> <li :key="item.id">{{item.name}}</li> </ul> <button @click="xiugai">点击修改数组</button> </div> </template>
arr: [ {name: 'aa', id: 1}, {name: 'bb', id: 2}, {name: 'cc', id: 3}, {name: 'dd', id: 4}, {name: 'ee', id: 5}, ]
xiugai() { let that = this; this.arr.push("lkk") }
这样点击button视图不会渲染;
受 ES5 的限制,Vue.js 不能检测到对象属性的添加或删除,即Vue未做到脏数据检查。因为 Vue.js 在初始化实例时将属性转为 getter/setter,所以属性必须在 data 对象上才能让 Vue.js 转换它,才能让它是响应的。
正确写法:
xiugai() { let that = this; this.arr.forEach(function(item, index){ that.$set(item, 'name', 'aaa') }) }
使用set也可以添加属性
xiugai() { let that = this; this.arr.forEach(function(item, index){ that.$set(item, 'age', index+1) }) }
调用方法:Vue.set( target, key, value )
target:要更改的数据源(可以是对象或者数组)
key:要更改的具体数据,也可以是要添加的数据
value :重新赋的值或者增加的值