vue系列生命週期(四)

vue生命週期,是指vue實例從創建到銷燬的一個過程,掌握了這個過程中各個階段的狀態,就能合理使用,是我們的程序性能更高,開發更合理,減少bug。
我們先看一張官方的vue的生命週期的圖:
vue生命週期
可以看到,vue實例生命週期分爲:beforeCreate,created,beforeMount,mounted,beforeUpdate,updated,activated,deactivated,beforeDestroy,destroyed,errorCaptured。下面我們再看看各個週期的含義,及平常我們的用途。
各個週期的作用

這裏說明一下,createdmounted2個階段的區別。created的時候,dome節點並沒有加載,如果做一些dome從操作,如document.getElementById時是獲取不到元素的。mounted能獲取到dome節點,但也不完全加載完,完全加載完可以放到this.$nextTick()的回調裏面。

下面看一個完整的實例,來表明各個週期的執行情況。

<!doctype html>
<html lang="en">
<head>
    <title>vue生命週期測試</title>
</head>
<body>
<div id="test">
    <h3>單組件</h3>
    <span>{{testData}}</span>
    <button @click="testData += 1">更新data裏面的值</button>
    <button @click="destroyVue">銷燬VUE實例</button>
</div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17-beta.0/vue.js"></script>
<script>
    new Vue({
        el: "#test",
        data() {
            return {
                testData: 0
            }
        },
        beforeCreate() {
            console.log("beforeCreate")
        },
        created() {
            console.log("created")
        },
        beforeMount() {
            console.log("beforeMount")
        },
        mounted() {
            console.log("mounted")
        },
        beforeUpdate() {
            console.log("beforeUpdate")
        },
        updated() {
            console.log("updated")
        },
        beforeDestroy() {
            console.log("beforeDestroy")
        },
        destroyed() {
            console.log("destroyed")
        },
        methods: {
            destroyVue() {
                this.$destroy()
            }
        }
    })
</script>
</html>

可以看到vue實例創建時,馬上執行了:
創建執行
我們點擊按鈕,更新data裏面的數據是,執行了下面的鉤子:
更新data
我們再銷燬vue實例,執行情況如下:
銷燬
上面的實例可以看到各種鉤子的執行情況,瞭解各個鉤子的作用和執行時機,合理運用,有助於我們的合理開發。
想看更多文章,可以關注我的個人公衆號:
公衆號

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