由于 JavaScript 的限制,Vue 不能检测数组和对象的变化。尽管如此我们还是有一些办法来回避这些限制并保证它们的响应性。
对于已经创建的实例,Vue 不允许动态添加根级别的响应式 但是,可以使用 Vue.set(object, "属性名", value)
方法向嵌套对象添加响应式。
关于对象:
Vue.set(Object, 'name', 2)
//刚接触可以尝试这种写法
let newObject= {...Object,'age':18,name:"张三"}
有时你可能需要为已有对象赋值多个新属性,比如使用 Object.assign()
或 _.extend()
。但是,这样添加到对象上的新 属性 不会触发更新。在这种情况下,你应该用原对象与要混合进去的对象的 属性 一起创建一个新的对象。
// 代替 `Object.assign(this.someObject, { a: 1, b: 2 })`
this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 })
关于数组:
Vue 不能检测这种数组的变动,
- 当你利用索引直接设置一个数组项时,例如:
list[index] = newValue
- 当你修改数组的长度时,例如:
list.length = newLength
为了解决第一类问题,vm.items[indexOfItem] = newValue
相同的效果,同时也将在响应式系统内触发状态更新:
// Vue.set
Vue.set(list, index, newValue)
// Array.prototype.splice
this.list.splice(index, 1, newValue)
为了解决第二类问题,你可以直接使用 splice
:
this.listthis.list.splice(newLength)
最后总结一些能够vue重写响应式的方法:
//添加
this.list.push(),
this.list.unshift(),
//删除
this.list.pop(),
this.list.shift(),
//截取
this.list.splice('索引','个数'),
//更新数据
this.list.splice('索引','个数','更改的数据'),
//排序
this.list.sort(),
//反转
this.list.reverse()