Vue實例生命周期鈎子函數執行順序


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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue生命周期鈎子</title>
    <style>
        [v-cloak] {
            display: none;
        }
    </style>
</head>

<body>
    <div id="app" v-cloak>
        <p v-html="message" ref="msg" v-once :style="setStyle"></p>
        <p><button type="button" @click="changeMessage()">修改</button></p>
        <p><button type="button" @click.once="destoryVue()">銷毀</button></p>

    </div>
</body>
<script src="https://cdn.bootcss.com/vue/2.6.11/vue.js"></script>
<script>

    var vm = new Vue({
        data: {
            message: '聽聞遠方有你 動身跋涉千里<br/> 我吹過你吹過的風 這算不算相擁<br/> 我踏過你踏過的路 這算不算相逢<br/> 我還是喜歡你 認真且慫 從一而終',
            count:0,
        },
        methods: {
            changeMessage() {
                this.message = this.$refs.msg.innerHTML+(this.count++);
                console.log('成功修改數據');
            },
            destoryVue() {
                this.$destroy();
                console.log('成功銷毀Vue實例');
            }
        },
        computed: {
            setStyle() {
                return {
                    'font-family': 'Times New Roman, Times, serif',
                    'color': 'darkblue',
                    'font-size': 'large',
                }
            }
        },
        watch: {
            message: function (newValue, oldValue) {
                console.log('監視數據變化:原值:' + newValue + '------新值:' + oldValue);
            }
        },
        beforeCreate() {
            console.log('beforeCreate-------創建實例之前執行的鈎子事件');
        },
        created() {
            console.log('created-------實例創建完成后執行的鈎子');
        },
        beforeMount() {
            console.log('beforeMount--------將編譯完成的HTML掛載到對應虛擬DOM時觸發的鈎子(此時頁面並沒有內容)');
        },
        mounted() {
            console.log('mounted-------編譯好的HTML掛載到頁面完成后執行的事件鈎子,此時鈎子函數中一般會做一些ajax請求獲取數據,進行數據初始化(mounted在整個實例中只會執行一次)');
        },
        beforeUpdate() {
            console.log('beforeUpdate-----更新視圖之前的鈎子');
        },
        updated() {
            console.log('updated------更新視圖之后的鈎子');
        },
        beforeDestroy() {
            console.log('beforeDestroy----實例銷毀之前執行的鈎子');
        },
        destroyed() {
            console.log('destroyed---------實例銷毀完成執行的鈎子');
        },


    }).$mount('#app');

</script>

</html>

 

https://cn.vuejs.org/v2/guide/instance.html#%E5%AE%9E%E4%BE%8B%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E9%92%A9%E5%AD%90

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM