代码之家  ›  专栏  ›  技术社区  ›  alex

如何使以下Vue代码具有响应性?

  •  1
  • alex  · 技术社区  · 7 年前

    在此代码中:

    handleChangeTab (toName, toIndex) {
      this.tabList.forEach((tab, index) => {
        tab.active = false
        this.$children[index].prefs.active = false
        if (tab.name === toName) {
          this.$children[toIndex].prefs.active = true
          tab.active = true
          console.log('tabList', this.tabList)
          console.log('this.$children', this.$children)
        }
      })
    },
    

    this.tabList[1].active 变成 true 什么时候? handleChangeTab 被触发。然而, this.$children[1] 变成 false .我想 this.$children[toIndex].prefs.active = 正在干扰Vue的反应特性。

    如何解决这个问题?换句话说,如何编写 this.$children[toIndex].prefs.active = true 是吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   ittus    7 年前

    handleChangeTab (toName, toIndex) {
      const tabCopy = JSON.parse(JSON.stringify(this.tabList))
      tabCopy.forEach((tab, index) => {
        tab.active = false
        this.$children[index].prefs = {
          ...this.$children[index].prefs,
          active: false
        }
    
        if (tab.name === toName) {
          this.$children[index].prefs = {
            ...this.$children[index].prefs,
            active: true
          }
          tab.active = true
        }
      })
      this.tabList = tabCopy
    }