Vue 实例生命周期
生活随笔
收集整理的這篇文章主要介紹了
Vue 实例生命周期
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一、生命周期
Vue 應(yīng)用都是通過 Vue 實(shí)例(ViewModel)完成的,Vue 創(chuàng)建實(shí)例需要一系列的初始化動(dòng)作,需要設(shè)置數(shù)據(jù)監(jiān)聽、編譯模板、將實(shí)例掛載到 DOM 并在數(shù)據(jù)變化時(shí)更新 DOM 等。當(dāng)然創(chuàng)建實(shí)例只是生命周期的一部分。
在 Vue 對(duì)象聲明周期的每個(gè)階段都會(huì)運(yùn)行一些叫生命周期的鉤子函數(shù),在對(duì)應(yīng)的鉤子函數(shù)中,可以添加自己的代碼以達(dá)到某種特定的功能。
鉤子函數(shù):
- beforeCreate:Vue 實(shí)例初始化之后執(zhí)行,但是此時(shí) Vue 實(shí)例數(shù)據(jù)與 el 數(shù)據(jù)都為空
- created:Vue 實(shí)例中的數(shù)據(jù)已經(jīng)綁定,但是 el 為空
- beforeMount:在 el 掛載之前執(zhí)行
- mounted:此時(shí) el 已經(jīng)被掛載到指定的 DOM 節(jié)點(diǎn)
- beforeUpdate:Vue 實(shí)例數(shù)據(jù)更新之后執(zhí)行,但是頁面中的數(shù)據(jù)并沒有更新
- updated:頁面數(shù)據(jù)更新之后執(zhí)行
- beforeDestroy:Vue 實(shí)例銷毀之前執(zhí)行
- destroyed:實(shí)例銷毀之后執(zhí)行
二、代碼演示
我們通過對(duì)應(yīng)的鉤子函數(shù)來說明 Vue 對(duì)象的生命周期,你可以拷貝下面的代碼,在控制臺(tái)觀察運(yùn)行結(jié)果
HTML 代碼
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Vue實(shí)例_生命周期</title> </head> <body> <div id="test"><p>更新次數(shù):{{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()')},// 在掛載之后執(zhí)行一個(gè)定時(shí)任務(wù),不斷地顯示與隱藏 'Hello Vue.js'mounted() {console.log('mounted()')this.intervalId = setInterval(() => {// 更新 'count',觸發(fā) beforeUpdate() 與 updsted()this.count ++}, 1000)},beforeUpdate() {console.log('beforeUpdate() ' + this.count)},updated () {console.log('updated() ' + this.count)},// 在對(duì)象銷毀之前,清除定時(shí)任務(wù)beforeDestroy() {console.log('beforeDestroy()')clearInterval(this.intervalId)},destroyed() {console.log('destroyed()')},// 給按鈕綁定一個(gè)事件:銷毀當(dāng)前 Vue 對(duì)象methods: {destroyVue () {this.$destroy()}}})</script>PS:
常用的鉤子函數(shù):
- mounted():用于發(fā)送 ajax 請(qǐng)求,啟動(dòng)定時(shí)任務(wù)等
- beforeDestory():做一些收尾工作,用于清除定時(shí)任務(wù)等
總結(jié)
以上是生活随笔為你收集整理的Vue 实例生命周期的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 环旭电子价值分析 有业内较强的核心竞争优
- 下一篇: vue 3.0和2.0区别_一文看懂 V