VUE 3 代碼的變化

在 Vue2 中如果我需要請(qǐng)求一份數(shù)據(jù),并且在loading和error時(shí)都展示對(duì)應(yīng)的視圖,一般來(lái)說(shuō),我們會(huì)這樣寫(xiě):

<template>
  <div>
    <div v-if="error">failed to load</div>
    <div v-else-if="loading">loading...</div>
    <div v-else>hello {{fullName}}!</div>
  </div>
</template>

<script>
import { createComponent, computed } from 'vue'

export default {
  data() {
    // 集中式的data定義 如果有其他邏輯相關(guān)的數(shù)據(jù)就很容易混亂
    return {
        data: {
            firstName: '',
            lastName: ''
        },
        loading: false,
        error: false,
    },
  },
  async created() {
      try {
        // 管理loading
        this.loading = true
        // 取數(shù)據(jù)
        const data = await this.$axios('/api/user')
        this.data = data
      } catch (e) {
        // 管理error
        this.error = true
      } finally {
        // 管理loading
        this.loading = false
      }
  },
  computed() {
      // 沒(méi)人知道這個(gè)fullName和哪一部分的異步請(qǐng)求有關(guān) 和哪一部分的data有關(guān) 除非仔細(xì)閱讀
      // 在組件大了以后更是如此
      fullName() {
          return this.data.firstName + this.data.lastName
      }
  }
}
</script>

這段代碼,怎么樣都談不上優(yōu)雅,湊合的把功能完成而已,并且對(duì)于loading、error等處理的可復(fù)用性為零。

數(shù)據(jù)和邏輯也被分散在了各個(gè)option中,這還只是一個(gè)邏輯,如果又多了一些邏輯,多了data、computed、methods?你如何迅速的分辨清楚這個(gè)method是和某兩個(gè)data中的字段關(guān)聯(lián)起來(lái)的?

讓我們把這段代碼的邏輯照搬到 Vue3 中,

看一下swr在 Vue3 中的表現(xiàn):

<template>
  <div>
    <div v-if="error">failed to load</div>
    <div v-else-if="loading">loading...</div>
    <div v-else>hello {{fullName}}!</div>
  </div>
</template>

<script>
import { createComponent, computed } from 'vue'
import useSWR from 'vue-swr'

export default createComponent({
  setup() {
      // useSWR幫你管理好了取數(shù)、緩存、甚至標(biāo)簽頁(yè)聚焦重新請(qǐng)求、甚至Suspense...
      const { data, loading, error } = useSWR('/api/user', fetcher)
      // 輕松的定義計(jì)算屬性
      const fullName = computed(() => data.firstName + data.lastName)
      return { data, fullName, loading, error }
  }
})
</script>


就是這么簡(jiǎn)單,邏輯更加聚合了。

順嘴一提, use-swr 的威力可遠(yuǎn)遠(yuǎn)不止看到的這么簡(jiǎn)單,隨便舉幾個(gè)它的能力:

間隔輪詢
請(qǐng)求重復(fù)數(shù)據(jù)刪除
對(duì)于同一個(gè) key 的數(shù)據(jù)進(jìn)行緩存
對(duì)數(shù)據(jù)進(jìn)行樂(lè)觀更新
在標(biāo)簽頁(yè)聚焦的時(shí)候重新發(fā)起請(qǐng)求
分頁(yè)支持
完備的 TypeScript 支持
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容