vue 列表渲染

在Vue官网中写道,vue无法直接用索引设置元素,

如 vm.items[0] = {}

提出的解决方法是用 :

example1.items.$set(0, { childMsg: 'Changed!'});

但是发现,如果用了这个方法之后,再使用vm.items[i]={};是有作用的。

同样vue中无法通过将数组长度制为0来让数组为空,只能使用

this.items.$remove(item);

此时去直接赋值是有效果的。

查看源码,vue提供的两种方法都是通过splice方法来实现,如下:

def(arrayProto, '$set', function $set(index, val) {
if (index >= this.length) {
this.length = Number(index) + 1;
}
return this.splice(index, 1, val)[0];
});

def(arrayProto, '$remove', function $remove(item) {
/* istanbul ignore if */
if (!this.length) return;
var index = indexOf(this, item);
if (index > -1) {
return this.splice(index, 1);
}
});

因此都是需要变异方法来改变变量的值

原文地址:https://www.cnblogs.com/Upton/p/5690798.html