在 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è)它的能力: