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

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

    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
      }

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

猜你喜欢

转载自blog.csdn.net/sjpeter/article/details/85279945