vue生命週期鉤子函式
阿新 • • 發佈:2020-12-29
技術標籤:vue
文章目錄
前言
vue所有的生命週期鉤子自動繫結 this 上下文到例項中,因此你可以訪問資料,對屬性和方法進行運算。這意味著 你不能使用箭頭函式來定義一個生命週期方法 (例如 created: () => this.fetchTodos())。這是因為箭頭函式綁定了父上下文,因此 this 與你期待的 Vue 例項不同, this.fetchTodos 的行為未定義
一、vue的生命週期是什麼
vue每個元件都是獨立的,每個元件都有一個屬於它的生命週期,從一個元件建立、資料初始化、掛載、更新、銷燬,這就是一個元件所謂的生命週期。在元件中具體的方法有:beforeCreate created beforeMount mounted beforeUpdate updated beforeDestroy destroyed
二、vue生命週期鉤子執行順序
<div id="app">
<h1>{{message}}</h1>
</div>
<script>
const app = new Vue({
el: "#app",
data: {
message: "hello world"
},
</script>
beforeCeate
beforeCreate () {
console.log("beforeCreate");
console.log(this.message); //undefined
console.log(this.$el);
console.log("-------------分割線-------------");
},
Vue的例項物件已經建立完畢 只是傳入的引數(data資料 methods方法 el 都沒有設定到Vue的例項上面去)所以這裡取不到data裡面的資料
created
created() {
console.log("created");
console.log(this.message);
console.log(this.$el);
console.log("-------------分割線-------------");
},
Vue例項物件建立完畢 並且所有的屬性 都已經設定到例項化物件上了(通常情況下可以做資料的初始化)
beforeMount
beforeMount() {
console.log("beforeMount");
console.log(this.message);
console.log(this.$el);
console.log("-------------分割線-------------");
},
頁面所有元件建立完畢,但是還沒有進行對應的VUE操作(data裡面資料的解析 methods裡面的方法 )僅限於拿到頁面結構(資料還沒有解析)
mounted
mounted() {
console.log("mounted");
console.log(this.message); //undefined
console.log(this.$el);
console.log("-------------分割線-------------");
}
頁面所有元件建立完畢 並且會執行對應的vue操作 把頁面(資料解析完畢)的結構掛到vue的例項上面
beforeUpdate
beforeUpdate() {
console.log("元件更新之前");
},
元件更新之前執行的鉤子函式
updated
updated() {
console.log("元件更新完成");
},
元件更新完成執行的鉤子函式
beforeDestroy
beforeDestroy() {
console.log("元件銷燬之前");
},
元件銷燬之前執行的鉤子函式
destroyed
destroyed() {
console.log("元件銷燬完成");
},
元件銷燬完成執行的鉤子函式