<div id="app">
  <div class="p-5">
    <h3>Vue 元件生命週期展示</h3>
    <button @click="isShowing = !isShowing" class="btn btn-primary">
      <span v-if="isShowing">隱藏元件</span>
      <span v-else>顯示元件</span>
    </button>
    {{isShowing}}
    <hr>
    <child v-if="isShowing"></child>
  </div>
</div>
const child = {
  template:`
  <div>
    <h4>{{ text }}</h4>
    <input type="text" class="form-control" v-model="text">
  </div>
  `,
  data: function () {
    return {
      text: 'Vue data 資料狀態'
    }
  },
  beforeCreate() {
    console.log(`beforeCreate! ${this.text}`);
  },
  created() {
    console.log(`created! ${this.text}`);
    alert(`created! ${this.text}`);
  },
  beforeMount() {
    alert(`beforeMount! ${this.text}`);
  },
  mounted() {
    alert(`mounted! ${this.text}`);
  },
  updated () {
    console.log(`updated! ${this.text}`);
  },
  activated () {
    alert(`activated! ${this.text}`);
  },
  deactivated () {
    alert(`deactivated! ${this.text}`);
  },
  beforeUnmount() {
    console.log(`beforeUnmount! ${this.text}`);
  },
  unmounted() {
    console.log(`unmounted! ${this.text}`);
  }
};
const App = {
  data() {
    return {
      isShowing: false
    }
  }
};
Vue.createApp(App).component('child',child).mount('#app');
Run Pen

External CSS

  1. https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/css/bootstrap.min.css

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.37/vue.global.prod.min.js