是的,每個(gè)Vue實(shí)例在被創(chuàng)建之前都要經(jīng)過(guò)一系列的初始化過(guò)程。例如需要配置數(shù)據(jù)觀測(cè)(data observe)、編譯模版、掛載實(shí)例到DOM,然后在數(shù)據(jù)變化時(shí)更新到DOM。在這些過(guò)程中,實(shí)例就會(huì)調(diào)用一些生命周期鉤子,這就給我們提供了執(zhí)行自定義邏輯的機(jī)會(huì)。
所以什么是生命周期鉤子???
beforeCreate、created、beforeMout、mouted、beforeUpdate、updated、beforeDestroy、destroyed這些都是鉤子(相當(dāng)于Vue實(shí)例在不同生命周期階段可以回調(diào)的函數(shù)),在這些鉤子里面可以自定義邏輯。當(dāng)然這些鉤子的this是指向調(diào)用它的Vue實(shí)例。
正如官網(wǎng)的流程圖:

代碼:
<section id="app">{{info}}</section>
<script>
var myVue=new Vue({
? ? ? el:"#app",
? ? ? data:{
? ? ? ? ? ? ? info:"good"
? ? ? ? },
? ? ? ? beforeCreate:function(){
? ? ? ? ? ? ? console.log("創(chuàng)建前========")
? ? ? ? ? ? ? console.log(this.info) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//undefined
? ? ? ? ? ? ? console.log(this.$el) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//undefined
? ? ? ? ?},
? ? ? ? ?created:function(){
? ? ? ? ? ? ? console.log("已創(chuàng)建========")
? ? ? ? ? ? ? console.log(this.info)? ? ? ? ? ? ? ? ? ? ? ? ? ? //good
? ? ? ? ? ? ? console.log(this.$el) ? ? ? ? ? ? ? ? ? ? ? ? ? ?//undefined
? ? ? ? ?},
? ? ? ? ?beforeMount:function(){
? ? ? ? ? ? ? console.log("mount之前========")
? ? ? ? ? ? ? console.log(this.info)? ? ? ? ? ? ? ? ? //good
? ? ? ? ? ? ? console.log(this.$el)? ? ? ? ? ? ? ? ? //[object HTMLDivElement] ? ? ?此時(shí)的$el是虛擬的DOM的節(jié)點(diǎn),<section>標(biāo)簽里面的文本還沒(méi)有被替換,還是<section id="app">{{info}}</section>
? ? ? ? ? },
? ? ? ? ?mounted:function(){
? ? ? ? ? ? ? ?console.log("mounted========")
? ? ? ? ? ? ? console.log(this.info)? ? ? ? ? ? ? //good
? ? ? ? ? ? ? console.log(this.$el)? ? ? ? ? ? ? //[object HTMLDivElement]? ? ? 此時(shí)的$el被替換了:<section id="app">good</section>
? ? ? ? ? },
? ? ? ? ?beforeUpdate:function(){
? ? ? ? ? ? ? console.log("更新前========");? ? ? //執(zhí)行 myVue.info="very good";觸發(fā)更新
? ? ? ? ?},
? ? ? ? ?updated:function(){
? ? ? ? ? ? ? console.log("更新完成========");? //更新完成? info的值為"very good"
? ? ? ? ? },
? ? ? ? ? beforeDestroy:function(){
? ? ? ? ? ? ? ? console.log("銷(xiāo)毀前========")? ? ? ? ? //執(zhí)行myVue.$destroy()觸發(fā)銷(xiāo)毀,實(shí)例銷(xiāo)毀之前調(diào)用。在這一步,實(shí)例仍然完全可用。
? ? ? ? ? ? ? ? console.log(this.info)? ? ? ? ? ? ? ? ? ? ? ? ? //good
? ? ? ? ? ? ? ? console.log(this.$el) ? ? ? ? ? ? ? ? ? ? ? ? ? //[object HTMLDivElement] ? ? ?<section id="app">good</section>
? ? ? ? },
? ? ? ? destroyed:function(){
? ? ? ? ? ? ? console.log("已銷(xiāo)毀========") ? ? ? ? //Vue 實(shí)例銷(xiāo)毀后調(diào)用。調(diào)用后,Vue 實(shí)例指示的所有東西都會(huì)解綁定,所有的事件監(jiān)聽(tīng)器會(huì)被移除,所有的子實(shí)例也會(huì)被銷(xiāo)毀。
? ? ? ? ? ? ? console.log(this.info)? ? ? ? ? ? ? ? ? ? ? ? ? //good
? ? ? ? ? ? ? console.log(this.$el)? ? ? ? ? ? ? ? ? ? ? ? ? //[object HTMLDivElement] ? ? <section id="app">good</sction>
? ? ? ?}
})
</script>>