Jun

只要我的心還會跳,腿還能動

我就沒有理由停下前進的步伐

Vue 生命週期


Vue 實例有一個完整的生命週期,包含從創建、初始化數據、編譯模板、掛載 DOM 至渲染、更新至渲染、移除等整個過程,稱之為 Vue 的生命週期。


beforeCreate
created
beforeMount
mounted
brforeUpdate
updated
beforeDestroy
destroyed
測試代碼
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
  <body>
    <div id="app">
      <h1>{{ count }}</h1>
      <button @click="updateHandler">加 1</button>
      <button @click="delInstance">刪除實例</button>
    </div>

    <script>
      var vm = new Vue({
        el: '#app',
        data: {
          count: 0,
        },
        methods: {
          updateHandler() {
            this.count += 1;
          },
          delInstance() {
            this.$destroy();
          },
        },
        beforeCreate() {
          console.log('beforeCreate --- this.count: ', this.count);
          console.log('beforeCreate --- this.$el: ', this.$el);
        },
        created() {
          console.log('created -------- this.count: ', this.count);
          console.log('created -------- this.$el: ', this.$el);
        },
        beforeMount() {
          console.log('beforeMount ---- this.count: ', this.count);
          console.log('beforeMount ---- this.$el: ', this.$el);
        },
        mounted() {
          console.log('mounted -------- this.count: ', this.count);
          console.log('mounted -------- this.$el: ', this.$el);
        },
        beforeUpdate() {
          console.log(
            'beforeUpdate: ',
            this.$el.querySelector('h1').innerText,
            this.count
          );
        },
        updated() {
          console.log(
            'updated: ',
            this.$el.querySelector('h1').innerText,
            this.count
          );
        },
        beforeDestroy() {
          console.log('beforeDestroy');
        },
        destroyed() {
          console.log('destroyed');
        },
      });
    </script>
  </body>
</html>