<!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"> <script src="./lib/vue.js"></script> <title>Document</title> </head> <body> <div id="app"> <input type="button" value="Button" @click="msg='No'"> <h3 id='h3'>{{msg}}</h3> </div> <script> var vm = new Vue( { el: '#app', data:{ msg:'ok' }, methods: { show(){ console.log('執行了') } }, beforeCreate() { //這是遇到的第一個生命周期函數表示實例完全會被創建出來,會執行 console.log(this.msg) //這時候console會顯示undefined this.show() //this.show is not a method //注意在beforeCreate生命周期函數執行的時候,data和methods中的數據都還沒有被初始化 }, created() { //這是遇到的第二個生命周期函數 console.log(this.msg) this.show() //在created中,data和methods都已經初始化好了 //如果要調用methods中的方法,最早只能在created中操作 }, beforeMount() { //這是遇到的第3個生命周期函數,表示模板已經編譯完成,但是尚未把模板渲染到頁面中去 console.log(document.getElementById('h3').innerText) //在beforeMount執行的時候,頁面中的元素沒有被真正替換過來,只是之前的一些模板字符串 }, mounted() { //這是遇到的第四個生命周期函數,表示內存中的模板,已經真實的掛載到了瀏覽器的頁面中,用戶已經看到了渲染好的頁面 console.log(document.getElementById('h3').innerText) //注意:mounted是實例創建中的最后一個生命周期函數,當執行完mounted,實例就完全被創建好了 }, beforeUpdate() { console.log('界面上元素的內容'+document.getElementById('h3').innerText) console.log('data中的msg數據是'+this.msg) }, updated() { console.log('界面上元素的內容' + document.getElementById('h3').innerText) console.log('data中的msg數據是' + this.msg) //頁面和data數據已經保持一致了 }, } ) </script> </body> </html> --------------------- 作者:晗曦靈澈 來源:CSDN 原文:https://blog.csdn.net/weixin_43208813/article/details/91077805 版權聲明:本文為博主原創文章,轉載請附上博文鏈接!