vue學(xué)習(xí)筆記(二)vue的生命周期和鉤子函數(shù)

前言

通過上一章的學(xué)習(xí),我們已經(jīng)初步的了解了vue到底是什么東西,可以干什么,而這一篇博客主要介紹vue的生命周期和它常用的鉤子函數(shù),如果有學(xué)過java的園友可能有接觸到在學(xué)習(xí)servlet的時候?qū)W過servlet的生命周期servlet 加載--->實例化--->服務(wù)--->銷毀,對于vue的而言他也有自己的生命周期,那么一起來看看吧!

本章目標

  • 學(xué)會并了解vue的生命周期和鉤子函數(shù)
  • 學(xué)會使用手動掛載和調(diào)用事件

vue的生命周期和鉤子函數(shù)

其實在提到vue的生命周期和鉤子函數(shù)的時候,有的人認為常用的鉤子函數(shù)有10個,也有的人認為是8個,無論是10個還是8個對于我而言都是一樣的,我們主要講解8個vue的鉤子函數(shù)。首先來一波官網(wǎng)的對于vue生命周期的圖解


image

這一張圖關(guān)于vue的生命周期已經(jīng)講解的特別到位了,但是光靠這一張圖還不足于了解它的生命周期,我們需要實踐一下,有句古話說的好,實踐是檢驗道理的唯一標準,介紹一下vue的鉤子函數(shù)。

image

beforeCreate(實例創(chuàng)建前)

實例組件剛開始創(chuàng)建,元素dom和數(shù)據(jù)都還沒有初始化
應(yīng)用場景:可以在這加個loading事件

created(實例創(chuàng)建后)

數(shù)據(jù)data已經(jīng)初始化完成,方法也已經(jīng)可以調(diào)用,但是dom為渲染,在這個周期里面如果進行請求是可以改變數(shù)據(jù)并渲染,由于dom未掛載,請求過多或者占用時間過長會導(dǎo)致頁面線上空白
應(yīng)用場景:在這結(jié)束loading,還做一些初始化,實現(xiàn)函數(shù)自執(zhí)行

beforeMoute(元素掛載前)

dom未完成掛載,數(shù)據(jù)初始化完成,但是數(shù)據(jù)的雙向綁定還是{{}},這是因為vue采用了虛擬dom技術(shù)。

mouted(元素掛載后)

數(shù)據(jù)和dom都完成掛載,在上一個周期占位的數(shù)據(jù)把值渲染進去,一般請求會放在這個地方,因為這邊請求改變數(shù)據(jù)之后剛好能渲染。

beforeUpdate(實例更新前)

只要是頁面數(shù)據(jù)改變了都會觸發(fā),數(shù)據(jù)更新之前,頁面數(shù)據(jù)還是原來的數(shù)據(jù),當你請求賦值一個數(shù)據(jù)的時候就會執(zhí)行這個周期,如果沒有數(shù)據(jù)改變不執(zhí)行。

updated(實例更新后)

只要是頁面數(shù)據(jù)改變了都會觸發(fā),數(shù)據(jù)更新完畢,頁面的數(shù)據(jù)是更新完成的,beforeUpdated和updated要謹慎使用,因為頁面更新數(shù)據(jù)的時候都會觸發(fā),在這里操作數(shù)據(jù)很影響性能和死循環(huán)。

beforeDestory(實例銷毀前)

實例銷毀之前調(diào)用,在這一步,實例仍然完全可用。

destory(實例銷毀后)

vue實例銷毀后調(diào)用,調(diào)用后,vue實例指示的所有內(nèi)容都會解除綁定,所有的事件監(jiān)聽器都會被移除,所有的子實例也會被銷毀。

實例一

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>vue的生命周期實例一</title>
    </head>
    <body>
        <div id="app">
            <input type="text" v-model="msg" />
            {{msg}}
        </div>
        <button onclick="destory()">銷毀</button>
        <script src="../js/vue.min.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            const vm=new Vue({
                el:'#app',
                data:{
                    msg:'vue'
                },
                beforeCreate(){
                    console.log('vue實例創(chuàng)建前:'+this.msg+','+this.$el);
                    //    數(shù)據(jù)data和dom都還沒有初始化
                },
                created(){
                    console.log('vue實例創(chuàng)建后:'+this.msg+','+this.$el);
                    //數(shù)據(jù)dom初始化完成,dom還沒有初始化完成
                },
                beforeMount(){
                    console.log('元素掛載前:');
                    console.log(this.$el);
                },
                mounted(){
                    console.log('元素掛載后:');
                    console.log(this.$el);
                },
                beforeUpdate(){
                    console.log('實例更新前');
                    console.log(this.msg);
                    console.log(this.$el);
                },
                updated(){
                    console.log('實例更新后');
                    console.log(this.msg);
                    console.log(this.$el);
                },
                beforeDestroy(){
                    console.log('實例銷毀前');
                    console.log(this.msg);
                },
                destroyed(){
                    console.log('實例銷毀后');
                    console.log(this.msg);
                }
            });
            function destory(){
                vm.$destroy();
            }
        </script>
    </body>
</html>

結(jié)果:


image

image

實例二

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>vue的生命周期實例二</title>
    </head>
    <body>
        <div id="app">
            {{name}}
        </div>
        <button onclick="destory()">銷毀實例</button>
        <script src="../js/vue.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            const vm=new Vue({
                el:'#app',
                data:{
                    name:'一只流浪的kk',
                    age:18
                },
                beforeCreate(){
                    console.log('============實例創(chuàng)建前=============');
                    console.log(this.$el);    //undefined
                    console.log(this.$data);//undefined
                },
                created(){
                    console.log('============實例創(chuàng)建后=============');
                    console.log(this.$el);
                    console.log(JSON.stringify(this.$data));
                },
                beforeMount(){
                    console.log('============元素掛載前=============');
                    console.log(this.$el);    
                    console.log(JSON.stringify(this.$data));
                },
                mounted(){
                    console.log('============元素掛載后=============');
                    console.log(this.$el);    
                    console.log(JSON.stringify(this.$data));
                },
                beforeUpdate(){
                    console.log('============實例更新前=============');
                    console.log(this.$el);    
                    console.log(JSON.stringify(this.$data));
                },
                updated(){
                    console.log('============實例更新后=============');
                    console.log(this.$el);    
                    console.log(JSON.stringify(this.$data));
                },
                beforeDestroy(){
                    console.log('============實例銷毀前=============');
                    console.log(this.$el);    
                    console.log(JSON.stringify(this.$data));
                },
                destroyed(){
                    console.log('============實例銷毀后=============');
                    console.log(this.$el);    
                    console.log(JSON.stringify(this.$data));
                }
            });
            function destory(){
                vm.$destroy();
            }
        </script>
    </body>
</html>
image

總結(jié)

  • beforeCreate() : 此時$el、data 的值都為undefined,即el 和 data 并未初始化 。
  • create(): 此時可以拿到data的值,但是$el依舊為undefined,即data完成了 數(shù)據(jù)的初始化,el沒有。
  • beforeMounte(): $el的值為“虛擬”的元素節(jié)點,dom未完成掛載,數(shù)據(jù)初始化完成,但是數(shù)據(jù)的雙向綁定還是{{}},這是因為vue采用了虛擬dom技術(shù)。
  • mouted(): 數(shù)據(jù)和dom都完成掛載,在上一個周期占位的數(shù)據(jù)把值渲染進去,一般請求會放在這個地方,因為這邊請求改變數(shù)據(jù)之后剛好能渲染。


    image

vue實例的手動掛載和調(diào)用事件

  • vm.$mount( [elementOrSelector] ) 如果 Vue 實例在實例化時沒有收到 el 選項,則它處于“未掛載”狀態(tài),沒有關(guān)聯(lián)的 DOM 元素??梢允褂?vm.$mount() 手動地掛載一個未掛載的實例,學(xué)習(xí)手動掛載和調(diào)用事件之前,我提取了一些vue實例常用的屬性和方法,帶有前綴 $ 便于與代理的data區(qū)分。
  • vm.$el:類型(HTMLElement)掛載元素,Vue實例的DOM根元素;即vm.$el===document.getElementById('節(jié)點'),注意:相等的情況必須是實例創(chuàng)建之后才行,也就是created之后。
  • vm.$data:類型(Object),Vue實例觀察的數(shù)據(jù)對象。
  • vm.$props:類型(Object),當前組件接收到的 props 對象。Vue 實例代理了- 對其 props 對象屬性的訪問。
  • vm.$options:類型(Object),用于當前 Vue 實例的初始化選項。需要在選項中包含自定義屬性時會有用處。
  • vm.$parent:類型(Vue實例),父實例,如果當前實例有的話。
  • vm.$root:類型(Vue實例),當前組件樹的根 Vue 實例。如果當前實例沒有父實例,此實例將會是其自己。
  • vm.$children:類型(Array(Vue實例)),當前實例的直接子組件。需要注意 children 并不保證順序,也不是響應(yīng)式的。如果你發(fā)現(xiàn)自己正在嘗試使用 。children 來進行數(shù)據(jù)綁定,考慮使用一個數(shù)組配合 v-for 來生成子組件,并且使用 Array 作為真正的來源。
    官網(wǎng)地址https://cn.vuejs.org/v2/api/
    接下來是介紹手動掛載和調(diào)用事件的常用方法,共有三個
var MyComponent = Vue.extend({
template: '<div>Hello!</div>'
})
// 創(chuàng)建并掛載到 #app (會替換 #app)
new MyComponent().$mount('#app')
// 同上
new MyComponent({ el: '#app' })
// 或者,在文檔之外渲染并且隨后掛載
var component = new MyComponent().$mount()
document.getElementById('app').appendChild(component.$el)

示例:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>手動掛載和調(diào)用事件</title>
    </head>
    <body>
        <div id="app">
        </div>
        <button onclick="hanlderOne()">手動掛載方式一</button>
        <button onclick="hanlderTwo()">手動掛載方式二</button>
        <button onclick="hanlderThree()">手動掛載方式三</button>
        <script src="../js/vue.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            const vm=new Vue({
                data:{
                    name:'vue'
                },
                template:'<h2>{{name}}</h2>'
            })
            function hanlderOne(){
                //方法一,手動掛載到指定的dom
                vm.$mount("#app");
            }
            function hanlderTwo(){
                //手動掛載,觸發(fā)編譯
                vm.$mount();
                document.getElementById('app').appendChild(vm.$el);
            }
            function hanlderThree(){
                //擴展一個新的vue構(gòu)造器
                const component=Vue.extend({
                    template:'<h2>{{name}}</h2>'
                });
                const a=new component({
                    data:{
                        name:'vue'
                    },
                    el:'#app'
                })
            }
        </script>
    </body>
</html>

結(jié)果:


image

vm.$destroy() 完全銷毀一個實例。清理它與其它實例的連接,解綁它的全部指令及事件監(jiān)聽器,這個方法我們在示例中有使用過,大家可以查看前面的示例。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容