Vue入門九、Vue生命週期

先上圖:
Vue入門九、Vue生命週期

示例代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript" src="vue.js"></script>
<div id="app"></div>
<script type="text/javascript">
    var mytest = {
        template: `
                <div>測試 {{msg}}
                    <br>
                    <button @click="msg+='1'" >點一下數據會更新</button>
                </div>
            `,
        data() {
            return {
                msg: '嗯呢'
            }
        },

        // 組件創建前
        beforeCreate() {
            console.log('組件創建前')
            console.log(this.msg)
        },
        // 組件創建後
        created() {
            console.log('組件創建後')
            console.log(this.msg)
        },
        // Dom 掛載前
        beforeMount() {
            console.log('Dom掛載前')
            console.log(document.body.innerText)
        },
        // Dom 掛載後
        mounted() {
            console.log('Dom掛載後')
            console.log(document.body.innerText)
        },
        // 數據變更前
        beforeUpdate() {
            console.log('數據更新前')
            console.log(document.body.innerText)
        },
        // 數據變更後
        updated() {
            console.log('數據更新後')
            console.log(document.body.innerText)
        },
        // 組件銷燬前
        beforeDestroy() {
            console.log('組件銷燬前')
        },
        // 組件銷燬後
        destroyed() {
            console.log('組件銷燬後')
        },
        // 組件激活
        activated() {
            console.log('組件激活')
        },
        // 組件停用
        deactivated() {
            console.log('組件停用')
        }
    }
    new Vue({
        el: '#app',
        template: `
                <div>
                    <keep-alive><mytest v-if="mytestShow"></mytest></keep-alive>
                    <button @click="clickDestroy">組件銷燬</button>
</div>
            `,
        components: {
            mytest
        },
        data() {
            return {
                mytestShow: true
            }
        },
        methods: {
            clickDestroy() {
                this.mytestShow = !this.mytestShow
            }
        }
    })

</script>
</body>
</html>

在需要頻繁的創建和銷燬組件,如果用的是v-if,可以使用activated()deactivated()對組件進行激活和停用,前提是被操作組件要用<keep alive></keep alive>包裹
例:<keep-alive><mytest v-if="mytestShow"></mytest></keep-alive>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章