1. 程式人生 > >Vue2 生命週期 lifecycle

Vue2 生命週期 lifecycle

<!DOCTYPE html>
<html>
<head>
  <title>Welcome to Vue</title>
  <script src="https://unpkg.com/vue"></script>
</head>
<body><div id="app">{{msg}}</div>
<script>
var app = new Vue({
  el: '#app',
  data: {
    msg: 'created1',
  },
  beforeCreate() {
    console.log(
"beforeCreate ===", this.$el, this.msg, "loading事件"); }, created() { console.log("created ===", this.$el, this.msg, "初始化,實現函式自執行"); }, beforeMount() { this.msg = "mounted2"; console.log("beforeMount ===", this.$el, this.msg, " 建立vm.$el並將“el”替換為它。"); }, mounted() { setTimeout(()
=> { app.$destroy() }, 1000); console.log("mounted ===", this.$el, this.msg, " 發起後端請求,拿回資料,配合路由鉤子"); this.msg = "updated3"; }, beforeUpdate() { // this.msg = "updated3"; console.log("beforeUpdate ===", this.$el, this.msg, " 虛擬DOM重呈現和修補程式"); }, updated() { // this.msg = "updated3";
console.log("updated ===", this.$el, this.msg, " 更新"); }, beforeDestroy:function(){ this.msg = "destroyed4"; console.log("beforeDestroy===", this.$el, this.msg, " 確定要銷燬元件嗎?") }, destroyed:function(){ console.log("destroyed ===", this.$el, this.msg, " 觀察器、子元件和事件監聽器已拆卸。") } }) </script> </body> </html>

每個 Vue 例項在被建立時都要經過一系列的初始化過程——例如,需要設定資料監聽、編譯模板、將例項掛載到 DOM 並在資料變化時更新 DOM 等。同時在這個過程中也會執行一些叫做生命週期鉤子的函式,這給了使用者在不同階段新增自己的程式碼的機會。

比如 created 鉤子可以用來在一個例項被建立之後執行程式碼:

也有一些其它的鉤子,在例項生命週期的不同階段被呼叫,如 mounted、updated 和 destroyed。生命週期鉤子的 this 上下文指向呼叫它的 Vue 例項。