生命週期和鉤子函數

每一個vue實例在創建之前都需要一系列的初始化過程,如實例需要數據觀測(data observer),編譯模板,掛載實例到DOM上,以及數據更新和DOM渲染。
create(創建): beforeCreate 創建前 ; created 創建結束
mount(掛載): beforeMount ;mounted
update(更新): beforeUpdate;Updated
destory(銷燬): beforeDestory;destoryed
鉤子函數:
在實例的生命週期中會自動執行一些函數,這些函數 就叫做鉤子函數
鉤子函數爲我們提供了,自定義一些邏輯的機會
語法和測試:

beforeCreate: function(){
        //el vue實例使用的根dom元素,是隻讀的
        // $data vue觀察的數據對象,實例代理了其對$data的對象屬性的訪問
        console.group("創建前beforeCreate-------------------------");
        console.log("el:------"+this.$el);     // el:------undefined
        console.log("data:------"+this.$data);  //  data:------undefined
        console.log("msg:------"+this.msg);  //  msg:------undefined
    },
    created: function(){
        console.group("創建完成created-------------------------");
        console.log("el:------"+this.$el);  //el:------undefined
        console.log("data:------"+this.$data); // data:------[object Object]       
        console.log("msg:------"+this.msg);  // msg:------hello vue
    },  
    beforeMount: function(){
        console.group("掛載前beforeMount-------------------------");
        console.log("el:------"+this.$el); // 虛擬出一個div元素來進行佔位
        console.log("data:------"+this.$data);     
        console.log("msg:------"+this.msg);
    },
    mounted: function(){
        console.group("掛載後mounted-------------------------");
        console.log("el:------"+this.$el);
        console.log("data:------"+this.$data);     
        console.log("msg:------"+this.msg);
    },
    beforeUpdate: function(){  //console 瀏覽器控制檯進行測試
        console.group("數據更新前beforeUpdate-------------------------");
        console.log("el:------"+this.$el);
        console.log("data:------"+this.$data);     
        console.log("msg:------"+this.msg);
    },
    updated: function(){
        console.group("數據更新後Update-------------------------");
        console.log("el:------"+this.$el);
        console.log("data:------"+this.$data);     
        console.log("msg:------"+this.msg);
    },
    beforeDestory: function(){  // $destory  完全銷燬一個實例。解綁它的全部指令和事件監聽器。清理和其他實例的鏈接
        console.group("銷燬前beforeDestory-------------------------");
        console.log("el:------"+this.$el);
        console.log("data:------"+this.$data);     
        console.log("msg:------"+this.msg);
    },
    destoryed: function(){
        console.group("銷燬後到destoryed-------------------------");
        console.log("el:------"+this.$el);
        console.log("data:------"+this.$data);     
        console.log("msg:------"+this.msg);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章