下圖展示了實例的生命周期。你不需要立馬弄明白所有的東西,不過隨著你的不斷學習和使用,它
的參考價值會越來越高。?
VUE 的生命周期指的是組件在創建、運行和銷毀過程中所經歷的一系列事件,通過這些事件可以
讓開發者在不同階段進行相應的邏輯處理。VUE 組件的生命周期分為 8 個階段:
- beforeCreate:組件實例剛被創建,但是數據還未初始化。在這個階段,無法訪問到 data 和 methods 等組件屬性。
- created:組件的數據已經初始化完成,但是 DOM 元素還未生成。可以進行一些異步操作,如發送 AJAX 請求獲取數據等。
- beforeMount:組件即將被掛載到頁面上。在這個階段,所有的模板和組件都已經編譯成 render 函數,并準備好渲染。
- mounted:組件已經掛載到頁面上,此時可以訪問到組件的 DOM 元素。可以進行一些需要訪問 DOM 元素的操作,如使用第三方插件等。
- beforeUpdate:組件更新之前被調用,在此時可以對組件進行更新前的狀態和數據進行處理。
- updated:組件更新完畢后被調用。在此階段中不能再更新組件的數據,否則會導致死循環。
- beforeDestroy:組件即將被銷毀,在此時可以進行一些清理工作,如清除定時器、解綁事件等。
- destroyed:組件已經被銷毀,此時所有的事件監聽和子組件都已經被移除。
掌握 VUE 組件的生命周期可以幫助開發者更好地理解組件的運行機制,在不同階段進行相應的邏
輯處理,從而實現更加靈活、高效的組件開發。
Vue到底是什么?優缺點是什么? - 知乎
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title>
</head><body><div id="app"><span id="num">{{num}}</span><button @click="num++">贊!</button><h2>{{name}},有{{num}}個人點贊</h2></div><script src="../node_modules/vue/dist/vue.js"></script><script>let app = new Vue({el: "#app",data: {name: "張三",num: 100},methods: {show() {return this.name;},add() {this.num++;}},beforeCreate() {console.log("=========beforeCreate=============");console.log("數據模型未加載:" + this.name, this.num);console.log("方法未加載:" + this.show());console.log("html模板未加載:" + document.getElementById("num"));},created: function () {console.log("=========created=============");console.log("數據模型已加載:" + this.name, this.num);console.log("方法已加載:" + this.show());console.log("html模板已加載:" + document.getElementById("num"));console.log("html模板未渲染:" + document.getElementById("num").innerText);},beforeMount() {console.log("=========beforeMount=============");console.log("html模板未渲染:" + document.getElementById("num").innerText);},mounted() {console.log("=========mounted=============");console.log("html模板已渲染:" + document.getElementById("num").innerText);},beforeUpdate() {console.log("=========beforeUpdate=============");console.log("數據模型已更新:" + this.num);console.log("html模板未更新:" + document.getElementById("num").innerText);},updated() {console.log("=========updated=============");console.log("數據模型已更新:" + this.num);console.log("html模板已更新:" + document.getElementById("num").innerText);}});</script>
</body></html>
?