穀粒商城學習——P42生命週期和鉤子函式
阿新 • • 發佈:2021-06-12
我簡單畫了一下
每個vue例項在被建立時都要經過一系列的初始化過程:建立例項,裝載模板、渲染模板等等。vue為生命週期中的每個狀態都設定了鉤子函式(監聽函式)。每當vue實列處於不同的生命週期時,對應的函式就會被觸發呼叫。
示例 :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"View Code> <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: { shows() {return this.name; }, }, beforeCreate() { console.log("=========beforeCreate============="); console.log("資料模型未載入:" + this.name, this.num); console.log("方法未載入:" + this.shows()); console.log("html模板未載入:" + document.getElementById("num")); }, created: function () { console.log("=========created============="); console.log("資料模型已載入:" + this.name, this.num); console.log("方法已載入:" + this.shows()); 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>