生活随笔
收集整理的這篇文章主要介紹了
VueJS生命周期
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一、生命周期
vue在生命周期中有這些狀態(tài),
beforeCreate,created,beforeMount,mounted,beforeUpdate,updated,beforeDestroy,destroyed。Vue
在實(shí)例化的過程中,會調(diào)用這些生命周期的鉤子,給我們提供了執(zhí)行自定義邏輯的機(jī)會。
vue對象初始化過程中,會執(zhí)行到beforeCreate,created,beforeMount,mounted 這幾個鉤子的內(nèi)容
beforeCreate :數(shù)據(jù)還沒有監(jiān)聽,沒有綁定到vue對象實(shí)例,同時也沒有掛載對象
created :數(shù)據(jù)已經(jīng)綁定到了對象實(shí)例,但是還沒有掛載對象
beforeMount: 模板已經(jīng)編譯好了,根據(jù)數(shù)據(jù)和模板已經(jīng)生成了對應(yīng)的元素對象,將數(shù)據(jù)對象關(guān)聯(lián)到了對象的
el屬性,el屬性是一個HTMLElement對象,也就是這個階段,vue實(shí)例通過原生的createElement等方法來創(chuàng)
建這個html片段,準(zhǔn)備注入到我們vue實(shí)例指明的el屬性所對應(yīng)的掛載點(diǎn)
mounted:將el的內(nèi)容掛載到了el,相當(dāng)于我們在jquery執(zhí)行了(el).html(el),生成頁面上真正的dom,上面我們
就會發(fā)現(xiàn)dom的元素和我們el的元素是一致的。在此之后,我們能夠用方法來獲取到el元素下的dom對象,并
進(jìn) 行各種操作
當(dāng)我們的data發(fā)生改變時,會調(diào)用beforeUpdate和updated方
beforeUpdate :數(shù)據(jù)更新到dom之前,我們可以看到$el對象已經(jīng)修改,但是我們頁面上dom的數(shù)據(jù)還
沒有發(fā)生改變
updated: dom結(jié)構(gòu)會通過虛擬dom的原則,找到需要更新頁面dom結(jié)構(gòu)的最小路徑,將改變更新到
dom上面,完成更新
beforeDestroy,destroed :實(shí)例的銷毀,vue實(shí)例還是存在的,只是解綁了事件的監(jiān)聽還有watcher對象數(shù)據(jù)
與view的綁定,即數(shù)據(jù)驅(qū)動
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>vue生命周期 </title><script type="text/javascript" src="js/vue-v2.6.10.js" ></script></head><body><div id="app"> {{message}}</div><script>//創(chuàng)建vue對象//鉤子函數(shù)(回調(diào)函數(shù)):不用手動調(diào)用的函數(shù)/** $.ajax({* url:"",* type:"",* data:"",* dataType:"",* success:function(){* * }* ,error:function(){* * }* * })*/var vm = new Vue({el:"#app", // 選擇器 $("#app")data:{message:"hello"},methods:{findAll:function(){}},beforeCreate: function() {console.log(this);showData('創(chuàng)建vue實(shí)例前', this);},created: function() {this.findAll();showData('創(chuàng)建vue實(shí)例后', this);},beforeMount: function() {showData('掛載到dom前', this);},mounted: function() {showData('掛載到dom后', this);},beforeUpdate: function() {showData('數(shù)據(jù)變化更新前', this);},updated: function() {showData('數(shù)據(jù)變化更新后', this);},beforeDestroy: function() {vm.test = "3333";showData('vue實(shí)例銷毀前', this);},destroyed: function() {showData('vue實(shí)例銷毀后', this);}});function showData(process, obj) {console.log(process);console.log('data 數(shù)據(jù):' + obj.test)console.log('掛載的對象:')console.log(obj.$el)realDom();console.log('------------------')console.log('------------------')}function realDom() {console.log('真實(shí)dom結(jié)構(gòu):' + document.getElementById('app').innerHTML);}vm.message="good...";vm.$destroy();
</script>
</body>
</html></script></body>
</html>
總結(jié)
以上是生活随笔為你收集整理的VueJS生命周期的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。