vue生命週期,是指vue例項從建立到銷燬的一個過程,掌握了這個過程中各個階段的狀態,就能合理使用,是我們的程式效能更高,開發更合理,減少bug。 我們先看一張官方的vue的生命週期的圖:

beforeCreate,created,beforeMount,mounted,beforeUpdate,updated,activated,deactivated,beforeDestroy,destroyed,errorCaptured
。下面我們再看看各個週期的含義,及平常我們的用途。

這裡說明一下,
created
和mounted
2個階段的區別。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例項建立時,馬上執行了:



