场景
当子数组里面的数据变化时,视图没有立即渲染。(如下图)
数组:路线
子数组:站点和车辆
遇到的问题
默认不显示车辆信息,鼠标悬浮车辆时,显示车辆信息。
是否显示车辆信息,我是通过将busDisplay 作为车辆信息中的字段来动态控制 display 样式。
所以当 mouseover 触发时,busDisplay 的值会发生变化。
刚开始处理方式: @mouseover="busDesOver(bus)" ,busDesOver(bus){ busbus.busDisplay='block'}
虽然 bus 数据更改了,但是视图没有立即渲染。
解决办法
vue.js官网的介绍:vue.js
// Vue.set Vue.set(example1.items, indexOfItem, newValue) |
// Array.prototype.splice example1.items.splice(indexOfItem, 1, newValue) |
部分源码
<el-card style='margin-bottom:15px;' v-for="(card, cardindex) in cardList">
<div class="line">
<div class="station-bus" v-for="(bus, index) of card.busList" :style="{left: bus.busSize}"
@mouseover="busDesOver(cardindex, index)" @mouseout="busDesOut(cardindex, index)">
<div class="el-popover bus-des" :style="{display: bus.busDisplay}">
车牌:{{bus.busNum}}
</div>
</div>
</div>
</el-card>
busDesOver(cardindex, index){
const cardTemp = this.cardList[cardindex]; // 通过父数组索引得到需要更改的数据
cardTemp.busList[index].busDisplay = 'block'; // 通过子数组索引更改实际变化的值
this.$set(this.cardList, cardindex, cardTemp); // 采取第一种方式
},
busDesOut(cardindex, index){
const cardTemp = this.cardList[cardindex];
cardTemp.busList[index].busDisplay = 'none';
// this.$set(this.cardList, cardindex, cardTemp);
this.cardList.splice(cardindex, 1, cardTemp); // 采取第二种方式
}
总结
1、vue 中监控 data 里定义的数据2、vue 只观察数组的变异方法。及只有变异方法才会触发视图更新。常用的如下:
- 增加数据:push()
- 修改/删除数据:splice()
其中,通过索引修改某一项时:
Vue.set(example1.items, indexOfItem, newValue)
example1.items.splice(indexOfItem, 1, newValue)
example1.items:数组(data里定义的数组)
indexOfItem:索引
newValue:更新之后的数据