javascript - 如何使以下 Vue 代码具有反应性?

标签 javascript vue.js

在这段代码中:

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)
    }
  })
},
handleChangeTab 被触发时,

this.tabList[1].active 变为 true。但是,this.$children[1] 变为 false。我认为 this.$children[toIndex].prefs.active = true 搞乱了 Vue 的响应式特性。

如何解决这个问题?换句话说,如何编写 this.$children[toIndex].prefs.active = true 的响应式版本?

最佳答案

可以尝试深拷贝数据:

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
}

但更好的解决方案是将 Prop 传递给您的子组件。不应直接从父级更改子级数据。

关于javascript - 如何使以下 Vue 代码具有反应性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50920375/

相关文章:

vue.js - VueJS : remove listener setup in view

javascript - 根据react js中的条件将值从一个函数传递到另一个函数

javascript - Sails.js:启用一些(但不是全部)REST 蓝图路由?

javascript - 如何让页面点击下滑而不刷新

javascript - 上标 .toFixed() 的结果

vue.js - 定位子组件的文本区域以复制到剪贴板

javascript - 如何清理空格和新行?

javascript - 带事件发射器的触发功能

javascript - 在 vuetify 中将覆盖层放在 fab 按钮上

vue.js - 使用任何功能之前, Uncaught Error : [vue-composition-api] must call Vue. use(plugin)