- 背景:組件需要重新加載,即重新走一遍組件的生命周期
- 常見解決方案:
- 使用v-if指令:v-if 可以實現 true (加載)和 false (卸載)
async reloadComponent() {this.show= false// 加上 nextTick this.$nextTick(function() {this.show= true})// 或者這種寫法// await this.$nextTick()// this.show = true
},
- 使用key屬性:Vue 的 key 屬性可以強制重新渲染組件。當組件的 key 值發生變化時,Vue 會銷毀舊的組件實例并創建一個新的。
// 組件綁定key
<ChildComponent :key="componentKey" />
// 更新key
reloadComponent() {this.componentKey += 1; // 修改 key 的值
},