Vue 实例生命周期
生活随笔
收集整理的這篇文章主要介紹了
Vue 实例生命周期
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、生命周期
Vue 應用都是通過 Vue 實例(ViewModel)完成的,Vue 創建實例需要一系列的初始化動作,需要設置數據監聽、編譯模板、將實例掛載到 DOM 并在數據變化時更新 DOM 等。當然創建實例只是生命周期的一部分。
在 Vue 對象聲明周期的每個階段都會運行一些叫生命周期的鉤子函數,在對應的鉤子函數中,可以添加自己的代碼以達到某種特定的功能。
鉤子函數:
- beforeCreate:Vue 實例初始化之后執行,但是此時 Vue 實例數據與 el 數據都為空
- created:Vue 實例中的數據已經綁定,但是 el 為空
- beforeMount:在 el 掛載之前執行
- mounted:此時 el 已經被掛載到指定的 DOM 節點
- beforeUpdate:Vue 實例數據更新之后執行,但是頁面中的數據并沒有更新
- updated:頁面數據更新之后執行
- beforeDestroy:Vue 實例銷毀之前執行
- destroyed:實例銷毀之后執行
二、代碼演示
我們通過對應的鉤子函數來說明 Vue 對象的生命周期,你可以拷貝下面的代碼,在控制臺觀察運行結果
HTML 代碼
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Vue實例_生命周期</title> </head> <body> <div id="test"><p>更新次數:{{count}}</p><button @click="destroyVue">destory vue</button> </div> </body> </html>Vue.js 代碼
<!-- 引入本地的 Vue.js --> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript">new Vue({el: '#test',data: {count: 0},beforeCreate() {console.log('beforeCreate()')},created() {console.log('created()')},beforeMount() {console.log('beforeMount()')},// 在掛載之后執行一個定時任務,不斷地顯示與隱藏 'Hello Vue.js'mounted() {console.log('mounted()')this.intervalId = setInterval(() => {// 更新 'count',觸發 beforeUpdate() 與 updsted()this.count ++}, 1000)},beforeUpdate() {console.log('beforeUpdate() ' + this.count)},updated () {console.log('updated() ' + this.count)},// 在對象銷毀之前,清除定時任務beforeDestroy() {console.log('beforeDestroy()')clearInterval(this.intervalId)},destroyed() {console.log('destroyed()')},// 給按鈕綁定一個事件:銷毀當前 Vue 對象methods: {destroyVue () {this.$destroy()}}})</script>PS:
常用的鉤子函數:
- mounted():用于發送 ajax 請求,啟動定時任務等
- beforeDestory():做一些收尾工作,用于清除定時任務等
總結
以上是生活随笔為你收集整理的Vue 实例生命周期的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 环旭电子价值分析 有业内较强的核心竞争优
- 下一篇: 银行贷款黑名单有什么影响