
lifecycle.png
<!DOCTYPE html>
<html>
<header>
<meta charset="utf-8"/>
<title></title>
<script src="./vue.js"></script>
</header>
<body>
<div id="app">
<button @click="message='下班'">修改data</button>
<h3 id="h3">{{message}}</h3>
</div>
<script>
var vm = new Vue({
el:"#app",
data:{
message:"我是message",
},
methods:{
show:function(){
console.log("this is show function")
}
},
beforeCreate(){//這是遇到的第一個(gè)生命周期函數(shù),表示實(shí)例完全被創(chuàng)建之前可以執(zhí)行它
//console.log(this.message);
///console.log(this.show());
//注意:在beforeCreate生命周期函數(shù)執(zhí)行的時(shí)候data和methods都還沒被初始化
},
created(){//這是遇到的第二個(gè)生命周期函數(shù)
console.log(this.message);
console.log(this.show());
//在created中data和methods都已經(jīng)初始化了
//如果要執(zhí)行methods中的方法,或者操作data中的數(shù)據(jù),最早只能在created中操作
},
beforeMount(){//這是遇到的第三個(gè)周期函數(shù),表示模板已經(jīng)編譯完成,但是尚未把模板渲染到頁(yè)面上
console.log(document.getElementById("h3").innerText)
//在beforeMount執(zhí)行的時(shí)候,頁(yè)面中的元素還沒有被替換過來,還是之前的
},
mounted(){//這是遇到的第四個(gè)生命周期函數(shù),內(nèi)存中的模板已經(jīng)渲染到頁(yè)面上,頁(yè)面已經(jīng)被渲染好了 ,mounted是實(shí)例創(chuàng)建期間的
//的最后一個(gè)函數(shù),當(dāng)執(zhí)行完mounted函數(shù),表示實(shí)例已經(jīng)完全創(chuàng)建好了,此時(shí),如果沒有其他操作的話,這個(gè)實(shí)例就靜靜的躺在內(nèi)存中,一動(dòng)不動(dòng)
},
//接下來的是運(yùn)行中的兩個(gè)事件
beforeUpdate(){
//這時(shí)候,表示我們的界面還沒有被更新[數(shù)據(jù)更新了嗎?更新了]
//console.log('界面上的元素內(nèi)容'+document.getElementById('h3').innerText);
//console.log("data數(shù)據(jù)"+this.message)
//結(jié)論:當(dāng)執(zhí)行beforeUpdate時(shí),頁(yè)面上的數(shù)據(jù)還是舊的,此時(shí)data數(shù)據(jù)是最新的,兩者尚未同步
},
updated(){
console.log('界面上的元素內(nèi)容:'+document.getElementById('h3').innerText);
console.log("data數(shù)據(jù):"+this.message)
//updated執(zhí)行時(shí),頁(yè)面和data的數(shù)據(jù)都已經(jīng)是最新的了
}
})
</script>
</body>
</html>