vue 关于双向绑定的坑之一数组无顺序插入

探讨了在Vue中处理异步数据加载时,数组直接赋值与push方法对组件刷新的影响,及如何通过整体更新数据来解决刷新问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用场景:异步获取数据,向数组内无顺序插入数据,通过双向绑定刷新组件或显示组件

    getList () {
        let that = this
        getCardsList('01').then((r) => {
          if (r.response !== "error") {
            // this.otherData = r
            for (let i in r) {
              getCardDetail(r[i].code).then((result) => {
                // console.log(result)
                // this.otherData.push(result)
                that.otherData[i] = result
              })
            }
          } else {
            this.$message.error(r.message);
          }
        })
      },

这是问题就出来了,数组使用push插入数据,组件能顺利刷新,但采用另一种写法a[i] = b,注意i受异步请求的影响,数组并不能保证顺序插入,那是否是插入顺序的影响呢?如下:

    getList () {
        let that = this
        getCardsList('01').then((r) => {
          if (r.response !== "error") {
            // this.otherData = r
            for (let i = 0; i <= 3; i++) {
              getCardDetail(r[i].code).then((result) => {
                // console.log(result)
                // this.otherData.push(result)
                that.otherData[i] = result
              })
            }
          } else {
            this.$message.error(r.message);
          }
        })
      },

但是实际修改后,组件还是不能正常显示。那么说明vue的双向绑定机制,在这种情况下失效了,于解决方案,就是尽量按照vue的双向绑定机制,整体更新数据,如下:

    getList () {
        let that = this
        let data = []
        getCardsList('01').then((r) => {
          if (r.response !== "error") {
            // this.otherData = r
            for (let i in r) {
              getCardDetail(r[i].code).then((result) => {
                // console.log(result)
                // this.otherData.push(result)
                data[i] = result
                that.getCardsLists(r, data)
              })
            }
          } else {
            this.$message.error(r.message);
          }
        })
      },
      getCardsLists (r, val) {
        for (let key in r) {
          if (!val[key]) {
            return
          }
        }
        this.otherData = val
      }

判断在所有需要的数据都拿到了以后,去给数组整体赋值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值