Vue3 入坑 Chapter 3

Vue3 入坑 Chapter 3

聲明周期

Vue2生命周期
vue2_lifecycle.png
Vue3聲明周期
vue3_lifecycle.jpg
Vue2 與 Vue3 版本生命周期相對應(yīng)的組合式 API

beforeCreate -> 使用 setup()
created -> 使用 setup()
beforeMount -> onBeforeMount
mounted -> onMounted
beforeUpdate -> onBeforeUpdate
updated -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed -> onUnmounted
errorCaptured -> onErrorCaptured

示例代碼

父組件中

<template>
  <div class="lifeCycleTest">
    <h2>APP父級組件</h2>
    <button @click="isShow=!isShow">切換顯示</button>
    <hr />
    <lifecycle-child-test v-if="isShow"></lifecycle-child-test>
    <hr />
    <lifecycle-child-test2 v-if="isShow"></lifecycle-child-test2>
  </div>
</template>

<script lang="ts">
import LifecycleChildTest from '@/components/LifecycleChildTest.vue'
import LifecycleChildTest2 from '@/components/LifecycleChildTest2.vue'
import { defineComponent, ref } from 'vue'

export default defineComponent({
  name: 'LifecycleTest',
  // 注冊組件
  components: {
    LifecycleChildTest,
    LifecycleChildTest2
  },
  setup () {
    const isShow = ref(true)
    return {
      isShow
    }
  }
})
</script>

<style lang="scss" scoped>

</style>

子組件1中(Vue2)

<template>
  <div class="LifecycleChildTest">
    <h2>Child子級組件, Vue2的用法</h2>
    <h4>msg: {{ msg }}</h4>
    <button @click="update">更新數(shù)據(jù)</button>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'

export default defineComponent({
  name: 'LifecycleChildTest',
  beforeCreate () {
    console.log('Vue2中的beforeCreate...')
  },
  created () {
    console.log('Vue2中的created...')
  },
  beforeMount () {
    console.log('Vue2中的beforeMount...')
  },
  mounted () {
    console.log('Vue2中的mounted...')
  },
  beforeUpdate () {
    console.log('Vue2中的beforeUpdate...')
  },
  updated () {
    console.log('Vue2中的updated...')
  },
  beforeUnmount () {
    console.log('Vue2中的beforeDestroy...')
  },
  unmounted () {
    console.log('Vue2中的created...')
  },
  setup () {
    // 響應(yīng)式數(shù)據(jù)
    const msg = ref('abc')
    // 按鈕點(diǎn)擊事件的回調(diào)
    const update = () => {
      msg.value += '==='
    }
    return { msg, update }
  }
})
</script>

<style lang="scss" scoped>

</style>

子組件2中(Vue3)

<template>
  <div class="LifecycleChildTest">
    <h2>Child子級組件2, Vue3的用法</h2>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue'

export default defineComponent({
  name: 'LifecycleChildTest',
  setup () {
    console.log('Vue3中的 setup')
    // 響應(yīng)式數(shù)據(jù)
    const msg = ref('abc')
    // 按鈕點(diǎn)擊事件的回調(diào)
    const update = () => {
      msg.value += '==='
    }
    onBeforeMount(() => {
      console.log('Vue3中的onBeforeMount...')
    })
    onMounted(() => {
      console.log('Vue3中的onMounted')
    })
    onBeforeUpdate(() => {
      console.log('Vue3中的onBeforeUpdate')
    })
    onUpdated(() => {
      console.log('Vue3中的onUpdated')
    })
    onBeforeUnmount(() => {
      console.log('Vue3中的onBeforeUnmount')
    })
    onUnmounted(() => {
      console.log('Vue3中的onUnmounted')
    })
  }
})
</script>

<style lang="scss" scoped>

</style>

自定義Hook函數(shù)

自定義Hook函數(shù): useMousePosition.ts

import { onBeforeUnmount, onMounted, ref } from 'vue'

// 此處應(yīng)該寫出函數(shù)的返回值類型
// eslint-disable-next-line
export default function () {
  const x = ref(-1)
  const y = ref(-1)

  // 點(diǎn)擊事件的回調(diào)函數(shù)
  const clickHandler = (event: MouseEvent) => {
    x.value = event.pageX
    y.value = event.pageY
  }

  // 頁面已經(jīng)加載完畢了, 再進(jìn)行點(diǎn)擊的操作
  // 頁面加載完畢的生命周期
  onMounted(() => {
    window.addEventListener('click', clickHandler)
  })

  // 頁面卸載之前的聲明周期組合API
  onBeforeUnmount(() => {
    window.removeEventListener('click', clickHandler)
  })
  return { x, y }
}

自定義Hook函數(shù): useRequest.ts (用于發(fā)送AJAX請求)

import { ref } from 'vue'
// 引入 axios
import axios from 'axios'
// 發(fā)送 ajax 請求, 此處應(yīng)該寫出函數(shù)的返回值類型
// eslint-disable-next-line
export default function <T> (url: string) {
  // 加載的狀態(tài)
  const loading = ref(true)
  // 請求成功的數(shù)據(jù)
  const data = ref<T | null>(null) // 坑
  // 錯誤信息
  const errorMsg = ref('')
  // 發(fā)送請求
  axios.get(url).then(rs => {
    // 改變加載狀態(tài)
    loading.value = false
    data.value = rs.data
  })
    .catch(error => {
      loading.value = false
      errorMsg.value = error.message || '未知錯誤'
    })
  return {
    loading,
    data,
    errorMsg
  }
}

業(yè)務(wù)組件中 CustomHookTest.vue

<template>
  <div class="customHookTest">
    <h2>自定義hook函數(shù)操作</h2>
    <h2>x: {{ x }}, y: {{ y }}</h2>
    <h3 v-if="loading">正在加載中...</h3>
    <h3 v-else-if="errorMsg">錯誤信息: {{ errorMsg }}</h3>
    <ul v-else>
      <li>id: {{ data.id }}</li>
      <li>address: {{ data.address }}</li>
      <li>distance: {{ data.distance }}</li>
    </ul>
    <hr>
    <!-- 數(shù)組數(shù)據(jù) -->
    <ul v-for="item in data" :key="item.id">
      <li>id: {{ item.id }}</li>
      <li>title: {{ item.title }}</li>
      <li>price: {{ item.price }}</li>
    </ul>
  </div>
</template>

<script lang="ts">
import { defineComponent, watch } from 'vue'
import useMousePosition from '@/hooks/useMousePosition'
import useRequest from '@/hooks/useRequest'

// 定義接口, 約束對象的類型
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface IAddressData {
  id: number,
  address: string,
  distance: string,
}

interface IProductData {
  id: string,
  title: string,
  price: number,
}

export default defineComponent({
  name: 'customHookTest',
  // 需求1: 用戶給在頁面中點(diǎn)擊頁面, 把點(diǎn)擊的位置的橫縱坐標(biāo)收集并展示出來
  setup () {
    const { x, y } = useMousePosition()
    // const { loading, data, errorMsg } = useRequest<IAddressData>('/mock/address.json') // 獲取對象數(shù)據(jù)
    const { loading, data, errorMsg } = useRequest<IProductData[]>('/mock/products.json') // 獲取數(shù)組數(shù)據(jù)
    // 監(jiān)視
    watch(data, () => {
      if (data.value) {
        console.log(data.value.length)
      }
    })
    return {
      x, y, loading, data, errorMsg
    }
  }
})
</script>

<style lang="scss" scoped>

</style>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末姑丑,一起剝皮案震驚了整個濱河市蛤签,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌栅哀,老刑警劉巖震肮,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異留拾,居然都是意外死亡戳晌,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進(jìn)店門痴柔,熙熙樓的掌柜王于貴愁眉苦臉地迎上來沦偎,“玉大人,你說我怎么就攤上這事咳蔚『篮浚” “怎么了?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵谈火,是天一觀的道長侈询。 經(jīng)常有香客問我,道長糯耍,這世上最難降的妖魔是什么扔字? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮温技,結(jié)果婚禮上革为,老公的妹妹穿的比我還像新娘。我一直安慰自己舵鳞,他們只是感情好震檩,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著系任,像睡著了一般恳蹲。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上俩滥,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天嘉蕾,我揣著相機(jī)與錄音,去河邊找鬼霜旧。 笑死错忱,一個胖子當(dāng)著我的面吹牛儡率,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播以清,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼儿普,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了掷倔?” 一聲冷哼從身側(cè)響起眉孩,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎勒葱,沒想到半個月后浪汪,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡凛虽,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年死遭,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片凯旋。...
    茶點(diǎn)故事閱讀 39,919評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡呀潭,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出至非,到底是詐尸還是另有隱情钠署,我是刑警寧澤,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布睡蟋,位于F島的核電站踏幻,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏戳杀。R本人自食惡果不足惜该面,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望信卡。 院中可真熱鬧隔缀,春花似錦、人聲如沸傍菇。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽丢习。三九已至牵触,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間咐低,已是汗流浹背揽思。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留见擦,地道東北人钉汗。 一個月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓羹令,卻偏偏與公主長得像,于是被迫代替她去往敵國和親损痰。 傳聞我的和親對象是個殘疾皇子福侈,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,864評論 2 354

推薦閱讀更多精彩內(nèi)容

  • 一些概念 Vue Composition API(VCA) 在實(shí)現(xiàn)上也其實(shí)只是把 Vue 本身就有的響應(yīng)式系統(tǒng)更顯...
    前端精閱讀 7,497評論 0 23
  • 是什么 vue2 的升級版, 使用 ts 重構(gòu)了代碼卢未, 帶來了 Composition API RFC肪凛。 類似于 ...
    小二兒上酒閱讀 734評論 0 3
  • 一文學(xué)會使用Vue3[https://www.cnblogs.com/qianduanpiaoge/p/14945...
    Never522閱讀 2,732評論 1 48
  • 全局API createApp 返回一個提供應(yīng)用上下文的應(yīng)用實(shí)例。應(yīng)用實(shí)例掛載的整個組件樹共享同一個上下文尝丐。 de...
    WangLizhi閱讀 2,497評論 0 0
  • 16宿命:用概率思維提高你的勝算 以前的我是風(fēng)險(xiǎn)厭惡者显拜,不喜歡去冒險(xiǎn),但是人生放棄了冒險(xiǎn)爹袁,也就放棄了無數(shù)的可能。 ...
    yichen大刀閱讀 6,049評論 0 4