理解 Vue 生命周期鉤子

參照翻譯 Understanding Vue.js Lifecycle Hooks

理解組件的生命周期,有利于我們了接到 vue 在創建組件的過程。以及使用生命周期鉤子賦予我們更多的能力。


lifecycle.png

創建(初始化階段)

創建鉤子是在您的組件中運行的第一個鉤子。 它們允許您在組件甚至在添加到DOM之前執行操作。 與任何其他鉤子不同,創建鉤子也在服務器端渲染期間運行。

如果您需要在客戶端呈現和服務器渲染期間在組件中設置東西,請使用創建掛鉤。同樣在創建鉤子忠 您將無法訪問模板。

beforeCreated

beforeCreate 鉤子在組件的初始化前運行。 data 還沒被附加上 reactvie 特型,events 也還沒建立好。

<script>
export default {
  beforeCreate() {
    console.log('Nothing gets called before me!')
  }
}
</script>

created

在 created 鉤子中,你能夠訪問 reactive data 和 events。但是模板和虛擬DOM無法訪問

export default {
    data: () => ({
        property: 'lys'
    }),

    computed: {
        propertyComputed() {
            console.log('I change when this.property changes.');
            return this.property;
        }
    },

    created() {
        this.property = 'laoergege';
        console.log(`propertyComputed is ${this.propertyComputed}`)
    }
}
result.png

掛載(插入到DOM階段)

Mounting hook 允許我們在組件渲染前后訪問組件。當然他們不會再服務端渲染被調用。如果您需要在初始化時為組件提取一些數據。 為此而使用created (or created + activated for keep-alive components),特別是如果在服務器端呈現期間需要該數據。

beforeMount

beforeMount鉤子在初始渲染發生之前和模板或渲染函數被編譯之后運行。

 beforeMount() {
        console.log(`this.$el doesn't exist yet, but it will soon!`);
        console.log(`this.$el is ${this.$el}`);
    }
image.png

mounted

使用 mounted 鉤子,你將擁有訪問組件模板能力。mounted 鉤子是經常使用的生命周期鉤子。我使用最多的方式是在 created 里獲取組件需要的數據或者在 mounted 中修改 DOM。

<template>
  <p>I'm text inside the component.</p>
</template>

<script>
export default {
  mounted() {
    console.log(this.$el.textContent) // I'm text inside the component.
  }
}
</script>

更新(數據監測并更新渲染)

每當您的組件使用的響應屬性更改或其他原因導致重新呈現時,將調用更新的鉤子。 它們允許您鉤入組件的watch-compute-render循環。
使用情況:如果您需要知道您的組件什么時候重新渲染,或許用于調試或分析。
避免情況:如果您需要知道組件上的 reactive 屬性何時更改。 為此而使用computed 屬性 或 watcher。

beforeUpdate

beforeUpdate 鉤子在您的組件的數據更改之后運行,更新周期開始,就在DOM修改和重新渲染之前。 它允許您在實際渲染之前獲取組件上任何反應數據的新狀態。

<script>
export default {
  data: () => ({
    counter: 0
  }),

  beforeUpdate() {
    console.log(this.counter) // Logs the counter value every second, before the DOM updates.
  },

  created() {
    setInterval(() => {
      this.counter++
    }, 1000)
  }
}
</script>

updated

更新的鉤子在您的組件和DOM重新呈現數據更改后運行。 如果您需要在屬性更改后訪問DOM,這可能是最安全的做法。

<template>
  <p ref="dom-element">{{counter}}</p>
</template>
<script>
export default {
  data: () => ({
    counter: 0
  }),

  updated() {
    // Fired every second, should always be true
    console.log(+this.$refs['dom-element'].textContent === this.counter)
  },

  created() {
    setInterval(() => {
      this.counter++
    }, 1000)
  }
}
</script>

銷毀

銷毀掛鉤允許您在組件銷毀時執行操作,例如清理或分析發送。 當您的組件被拆除并從DOM中刪除時,它們將觸發。

beforeDestory

beforeDestroy 在拆卸組件之前被回掉。 您的組件仍將完全存在。 如果您需要清理事件或取消訂閱,則可能是DDestroy可能要執行此操作。

<script>
export default {
  data: () => ({
    someLeakyProperty: 'I leak memory if not cleaned up!'
  }),

  beforeDestroy() {
    // Perform the teardown procedure for someLeakyProperty.
    // (In this case, effectively nothing)
    this.someLeakyProperty = null
    delete this.someLeakyProperty
  }
}
</script><script>
export default {
  data: () => ({
    someLeakyProperty: 'I leak memory if not cleaned up!'
  }),

  beforeDestroy() {
    // Perform the teardown procedure for someLeakyProperty.
    // (In this case, effectively nothing)
    this.someLeakyProperty = null
    delete this.someLeakyProperty
  }
}
</script>

destory

當 destory 鉤子被調用時,意味你的組件完全被銷毀。你可以利用最后這鉤子做些最后清理或者通知服務器該組件被銷毀了。

<script>
import MyCreepyAnalyticsService from './somewhere-bad'

export default {
  destroyed() {
    console.log(this) // There's practically nothing here!
    MyCreepyAnalyticsService.informService('Component destroyed. All assets move in on target on my mark.')
  }
}
</script>

其他鉤子(activated and deactivated)

還有另外兩個掛鉤,activated and deactivated。 這些是用于保持活動的組件,這個主題不在本文的范圍之內。 只要它們允許您檢測何時打開或關閉包含在<keep-alive> </ keep-alive>標簽中的組件。 您可以使用它們來獲取組件的數據或處理狀態更改,相當于 created 和 beforeDestroy,而無需執行完整的組件重建。

總結

Vue 組件的生命周期分為四個階段,每個階段有兩個生命鉤子,注意前后鉤子。

  • 創建階段:主要用于組件創建時,獲取數據設置組件。
  1. beforeCreate
  2. created(能夠訪問創建成功的組件實例,但不能訪問 模板,el 或 DOM)
  • 掛載階段:主要用于訪問組件 DOM。
  1. beforeMount
  2. mounted(能夠訪問組件模板)
  • 更新階段:數據變化,組件重新渲染。
  1. beforeUpdate(能夠訪問組件更新后的數據,但無法訪問 DOM)
  2. updated(能夠訪問 DOM)
  • 銷毀階段:(用于銷毀組件,做清理工作)
  1. beforeDestory(銷毀前還能訪問組件實例)
  2. destory
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容