每個(gè) Vue 實(shí)例在被創(chuàng)建之前都要經(jīng)過(guò)一系列的初始化過(guò)程送火。例如买乃,實(shí)例需要配置數(shù)據(jù)觀測(cè)(data observer)珍剑、編譯模版、掛載實(shí)例到 DOM 穆壕,然后在數(shù)據(jù)變化時(shí)更新 DOM 待牵。
(抱歉圖片無(wú)法加載否則會(huì)更詳細(xì) , 希望下面的介紹會(huì)對(duì)各位有所幫助)
beforeCreate,created,beforeMount,mounted,beforeUpdate,updated,beforeDestroy,destroyed喇勋。Vue在實(shí)例化的過(guò)程中缨该,會(huì)調(diào)用這些生命周期的鉤子,給我們提供了執(zhí)行自定義邏輯的機(jī)會(huì)川背。那么贰拿,在這些vue鉤子中蛤袒,vue實(shí)例到底執(zhí)行了那些操作,我們先看下面執(zhí)行的例子
var vm = new Vue({
el: "#container",
data: {
test : 'hello world'
},
beforeCreate: function(){
console.log(this);
showData('創(chuàng)建vue實(shí)例前',this);
},
created: function(){
showData('創(chuàng)建vue實(shí)例后',this);
},
beforeMount:function(){
showData('掛載到dom前',this);
},
mounted: function(){
showData('掛載到dom后',this);
},
beforeUpdate:function(){
showData('數(shù)據(jù)變化更新前',this);
},
updated:function(){
showData('數(shù)據(jù)變化更新后',this);
},
beforeDestroy:function(){
vm.test ="3333";
showData('vue實(shí)例銷毀前',this);
},
destroyed:function(){
showData('vue實(shí)例銷毀后',this);
}
});
function realDom(){
console.log('真實(shí)dom結(jié)構(gòu):' + document.getElementById('container').innerHTML);
}
function showData(process,obj){
console.log(process);
console.log('data 數(shù)據(jù):' + obj.test)
console.log('掛載的對(duì)象:')
console.log(obj.$el)
realDom();
console.log('------------------')
console.log('------------------')
}
每個(gè) Vue 實(shí)例在被創(chuàng)建之前都要經(jīng)過(guò)一系列的初始化過(guò)程膨更。例如妙真,實(shí)例需要配置數(shù)據(jù)觀測(cè)(data observer)、編譯模版荚守、掛載實(shí)例到 DOM 珍德,然后在數(shù)據(jù)變化時(shí)更新 DOM 。