<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue生命周期鈎子</title> <style> [v-cloak] { display: none; } </style> </head> <body> <div id="app" v-cloak> <p v-html="message" ref="msg" v-once :style="setStyle"></p> <p><button type="button" @click="changeMessage()">修改</button></p> <p><button type="button" @click.once="destoryVue()">銷毀</button></p> </div> </body> <script src="https://cdn.bootcss.com/vue/2.6.11/vue.js"></script> <script> var vm = new Vue({ data: { message: '聽聞遠方有你 動身跋涉千里<br/> 我吹過你吹過的風 這算不算相擁<br/> 我踏過你踏過的路 這算不算相逢<br/> 我還是喜歡你 認真且慫 從一而終', count:0, }, methods: { changeMessage() { this.message = this.$refs.msg.innerHTML+(this.count++); console.log('成功修改數據'); }, destoryVue() { this.$destroy(); console.log('成功銷毀Vue實例'); } }, computed: { setStyle() { return { 'font-family': 'Times New Roman, Times, serif', 'color': 'darkblue', 'font-size': 'large', } } }, watch: { message: function (newValue, oldValue) { console.log('監視數據變化:原值:' + newValue + '------新值:' + oldValue); } }, beforeCreate() { console.log('beforeCreate-------創建實例之前執行的鈎子事件'); }, created() { console.log('created-------實例創建完成后執行的鈎子'); }, beforeMount() { console.log('beforeMount--------將編譯完成的HTML掛載到對應虛擬DOM時觸發的鈎子(此時頁面並沒有內容)'); }, mounted() { console.log('mounted-------編譯好的HTML掛載到頁面完成后執行的事件鈎子,此時鈎子函數中一般會做一些ajax請求獲取數據,進行數據初始化(mounted在整個實例中只會執行一次)'); }, beforeUpdate() { console.log('beforeUpdate-----更新視圖之前的鈎子'); }, updated() { console.log('updated------更新視圖之后的鈎子'); }, beforeDestroy() { console.log('beforeDestroy----實例銷毀之前執行的鈎子'); }, destroyed() { console.log('destroyed---------實例銷毀完成執行的鈎子'); }, }).$mount('#app'); </script> </html>