最近想用vue来写项目,其中在创建data的时候我先创建了个空数组:
data () {
return {
items:[]
}
},
然后在create的时候,放数据进去:
for(var i = 0;i<30;i++){
this.items[i] = {
item:i,
blowUp:false,
show:0,
backgroundColor:'white',
}
}
这样写@click之类的通过method可以改变items的属性,但是页面没有显示出样式的变化。然后纠结了很久,在create的时候换了另外一种写法:
for(var i = 0;i<30;i++){
this.items.push({
item:i,
blowUp:false,
show:0,
backgroundColor:'white',
})
}
换成push之后,通过method改变items的属性可以实时在页面体现出来。
然后我在create之后,打印两者数据,发现是这样的
第一种:
第二种:
我实在不能理解为什么这两种写法会出现这样的区别,有没有大神可以解释下。。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
Vue重写了数组的以下方法:Array.prototype.pushArray.prototype.popArray.prototype.shiftArray.prototype.unshiftArray.prototype.spliceArray.prototype.sortArray.prototype.reverse并使用
Object.defineProperty把Object的属性全部转为getter/setter你可以打印一下
console.info(this.items.push)然后跟进代码查看http://cn.vuejs.org/v2/guide/list.html#变异方法
除了楼上说的外
Vue对
Object做了Observer用于监控数据的变化,这是和angularjs 1区别最大的地方,因为angularjs 1是复制了一套Object,实时用的新旧数据对比做的更新所以数组等操作要按照Vue规定的函数来
除了
push等方法外,还可以这么做