使用 :key 重新掛載組件 - daniel-qa/Vue GitHub Wiki

使用 :key 重新掛載組件

如果需要 完全重新創建子組件(重新跑生命週期、初始化 data),可以用 :key 強制 Vue 當作一個新組件來渲染:

<template>
  <div>
    <ChildComponent :key="childKey" />
    <button @click="reloadChild">重新掛載子組件</button>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue'

export default {
  components: { ChildComponent },
  data () {
    return {
      childKey: 0
    }
  },
  methods: {
    reloadChild () {
      this.childKey++  // 改變 key,Vue 會銷毀並重新建立組件
    }
  }
}
</script>

👉 這個方法會 觸發整個子組件重新掛載,適合需要完整 reset 狀態的情境。

⚠️ **GitHub.com Fallback** ⚠️