-
Notifications
You must be signed in to change notification settings - Fork 20
Open
Description
vue数据更新, 视图未更新
在使用 vue 过程中,可能经常有遇到 vm.items[i] = xxx
修改数据model之后,视图未更新重新渲染问题,基于这个问题:
Vue.js
不能检测到下面数组变化:
-
1.直接用索引设置元素,如 vm.items[indexOfItem] = newValue;
-
2.修改数据的长度,如 vm.items.length = newLength。
Vue.js 1.0
为了以上问题, 扩展了观察数组,为它添加了 $set()
和 $remove()
方法:
$set()
方法
// 与 `example1.items[0] = ...` 相同,但是能触发视图更新
example1.items.$set(0, { childMsg: 'Changed!'})
$remove()
方法, 用于从目标数组中查找并删除元素,在内部它调用 splice(), 那么:
var index = this.items.indexOf(item)
if (index !== -1) {
this.items.splice(index, 1)
}
//以上代码可以用这行替换
this.items.$remove(item)
Vue.js 2.0
1.解决第一种情况
// Vue.set
Vue.set(example1.items, indexOfItem, newValue)
// Array.prototype.splice`
example1.items.splice(indexOfItem, 1, newValue)
2.解决第二种情况直接使用 splice
example1.items.splice(newLength)
Vue.js
对于数组变动检测,还包装了被观察数组的变异方法。
数组变动检测
变异方法
Vue.js 包装了被观察数组的变异方法,故它们能触发视图更新。被包装的方法有:
- push()
- pop()
- shift()
- unshift()
- splice()
- sort()
- reverse()
小知识
: 其实是改变原有数组,整体变为改变属性变更。
重塑数组
变异方法(mutation method),顾名思义,会改变被这些方法调用的原始数组。相比之下,也有非变异(non-mutating method)方法,例如: filter()
, concat()
, slice()
。这些不会改变原始数组,但总是返回一个新数组。当使用非变异方法时,可以用新数组替换旧数组:
Metadata
Metadata
Assignees
Labels
No labels