爬坑日记--------vue之数组中数据变化,而视图未渲染(多层数组)

场景

 当子数组里面的数据变化时,视图没有立即渲染。(如下图)

数组:路线

子数组:站点和车辆


遇到的问题

 默认不显示车辆信息,鼠标悬浮车辆时,显示车辆信息。

是否显示车辆信息,我是通过将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:更新之后的数据

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值