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

Vue的生命周期

Vue示例被創(chuàng)建到銷毀的過程

Vue的鉤子函數(shù)詳解

<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Vue的聲明周期和鉤子函數(shù)</title>
</head>

<body>
    <div id="app">
        <button @click="win">control</button>
        {{msg}}
    </div>
    <script src="js/vue.js"></script>
    <script>
        let vm = new Vue({
            el: '#app',
            data: {
                msg: 'hello'
            },

            // template: "<h1>{{msg}}-------ok</h1>",
            methods: {
                win() {
                    alert('ok');
                }
            },

            // 生命周期(鉤子函數(shù) hook)函數(shù)就是vue實例在某一個時間點會自動執(zhí)行的函數(shù)

            // 此時vue實例已經(jīng)進(jìn)行了基礎(chǔ)的初始化,但data數(shù)據(jù)還沒有綁定到vue的實例,此時,訪問不到data數(shù)據(jù)
            beforeCreate() {
                console.log('beforeCreate', this.msg);
            },

            // 此時,data數(shù)據(jù)已經(jīng)注入vue的實例,我們可以通過this訪問到data數(shù)據(jù)
            created() {
                console.log('created', this.msg);
            },

            // 此時,模板和數(shù)據(jù)已經(jīng)結(jié)合,編譯,但還沒有掛載到指定的掛載點上 (或者沒有掛載到指定的頁面元素上)
            beforeMount() {
                console.log('beforeMount', this.$el);
            },

            // 此時,編譯后的模板已經(jīng)掛載到掛載點上,我們會看到加載了數(shù)據(jù)的視圖的更新
            mounted() {
                console.log('mounted', this.$el);
            },

            // 當(dāng)有數(shù)據(jù)發(fā)生改變時,模板重新渲染之前,會觸發(fā)該事件。
            beforeUpdate() {
                console.log('beforeUpdate', this.$el.innerHTML);
            },

            // 當(dāng)模板重新渲染之后,觸發(fā)該事件
            updated() {
                console.log('updated', this.$el.innerHTML);
            },

            // 當(dāng)執(zhí)行vm.$destroy(),vue實例銷毀之前發(fā)生
            beforeDestroy() {
                console.log('beforeDestroy');
            },

            //vue實例銷毀之后發(fā)生,此時再改變數(shù)據(jù),不會觸發(fā)視圖更新(或者視圖重新渲染)
            destroyed() {
                console.log('destroyed');
            }

        });

        //也可以通過vm.$mount注冊掛載點
        // vm.$mount('#app');
    </script>
</body>

</html>
?著作權(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)容