在这段代码中:
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/