vue2的生命周期詳解(代碼演示+源碼)2024-01-23

<template>

? <div>

? ? <div id="test">{{name}}</div>

? ? <el-button @click="name='點擊更新的內容'">更新內容</el-button>

? </div>

</template>

<script>

? export default {

? ? data() {

? ? ? return {

? ? ? ? name: '暴怒的代碼'

? ? ? }

? ? },

? ? render(h) {

? ? ? return h('div', [

? ? ? ? h('h1', this.name),

? ? ? ? h('button', {

? ? ? ? ? on: {

? ? ? ? ? ? click: () => {

? ? ? ? ? ? ? alert('點擊了我')

? ? ? ? ? ? }

? ? ? ? ? }

? ? ? ? }, 'Click me')

? ? ? ]);

? ? },

? ? beforeCreate() {

? ? ? console.log('------------------初始化階段------------------')

? ? ? //這里data 和 methods 中的數(shù)據(jù)還沒有初始化,所以輸出的應該是undefined

? ? ? console.log(`這是beforeCreate的執(zhí)行:${this.name}`)

? ? },

? ? created() {

? ? ? //這里數(shù)據(jù)已經(jīng)初始化了,可以輸出data中的內容

? ? ? console.log(`這是Create的執(zhí)行:${this.name}`)

? ? ? //因為在created()中還沒有渲染到DOM頁面,所以在渲染前修改,選的數(shù)據(jù)是下面的內容

? ? ? this.name = '在渲染到DOM之前就修改內容'

? ? },

? ? beforeMount() {

? ? ? console.log('------------------掛載階段------------------')

? ? ? //開始編譯數(shù)據(jù),但是當前數(shù)據(jù)只在內存中渲染,并沒有真實的渲染到html頁面上

? ? ? console.log(`這是beforeMount的執(zhí)行:${document.getElementById('test').innerText}`)

? ? },

? ? mounted() {

? ? ? //獲取到數(shù)據(jù),內存中的數(shù)據(jù)真實的掛載到頁面中,Vue實例創(chuàng)建完成

? ? ? console.log(`這是mounted的執(zhí)行:${document.getElementById('test').innerText}`)

? ? },

? ? beforeUpdate() {

? ? ? console.log('------------------更新階段------------------')

? ? ? //頁面上的數(shù)據(jù)還是以前的,內存中的數(shù)據(jù)是最新的

? ? ? console.log(`這是beforeUpdate的執(zhí)行,頁面數(shù)據(jù):${document.getElementById('test').innerText}`)

? ? ? console.log(`這是beforeUpdate的執(zhí)行,data數(shù)據(jù):${this.name}`)

? ? },

? ? updated() {

? ? ? //頁面上的數(shù)據(jù)和內存中的數(shù)據(jù)都是最新的

? ? ? console.log(`這是updated的執(zhí)行,頁面數(shù)據(jù):${document.getElementById('test').innerText}`)

? ? ? console.log(`這是updated的執(zhí)行,data數(shù)據(jù):${this.name}`)

? ? },

? ? beforeDestroy() {

? ? ? console.log('------------------銷毀階段------------------')

? ? ? // 仍可以使用data與method方法

? ? ? console.log(`這是beforeDestroy的執(zhí)行:${this.name}`)

? ? },

? ? destroyed() {

? ? ? // 已經(jīng)銷毀data與method方法

? ? ? console.log(`這是destroyed的執(zhí)行:${this.name}`)

? ? },

? }

</script>

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • Vue 生命周期 從生到死的過程,從Vue實例創(chuàng)建-運行-銷毀的過程 Vue實例有一個完整的生命周期,也就是從開始...
    前端菜菜1號閱讀 339評論 0 0
  • 什么是生命周期:從VUE實例創(chuàng)建、運行、到銷毀期間,總是伴隨著各種各樣的事件,這些事件,統(tǒng)稱為生命周期生命周期鉤子...
    7ColorLotus閱讀 292評論 0 1
  • beforeCreate 第一個生命周期函數(shù),表示實例完全被創(chuàng)建出來之前,會執(zhí)行它 注意: 在 beforeCre...
    donzi閱讀 299評論 0 0
  • 什么是生命周期:從Vue實例創(chuàng)建、運行到銷毀期間,總是伴隨著各種各樣的事件,這些事件,統(tǒng)稱為生命周期! 生命周期鉤...
    Flipped_kk閱讀 300評論 0 4
  • <!DOCTYPE html> Title {{msg}} /...
    點木子閱讀 87評論 0 0

友情鏈接更多精彩內容