使用 Pinia 的五個技巧,你知道幾個
在這篇文章中,想與大家分享使用 Pinia 的五大技巧。
以下是簡要總結(jié):
- 不要創(chuàng)建無用的 getter
- 在 Option Stores 中使用組合式函數(shù)(composables)
- 對于復(fù)雜的組合式函數(shù),使用 Setup Stores
- 使用 Setup Stores 注入全局變量,如路由器(Router)
- 如何創(chuàng)建私有狀態(tài)
1、不要創(chuàng)建無用的 getter
你并不需要為所有事情使用 getter。在 Vuex 中有一個普遍的誤解,認(rèn)為你應(yīng)該總是通過 getter 訪問狀態(tài)。
這是不正確的。
當(dāng)你需要從狀態(tài)中計(jì)算出某些東西時,getter 是有用的,例如,如果你有一個待辦事項(xiàng)列表,想知道有多少已完成,你可以為此創(chuàng)建一個 getter。
在生產(chǎn)代碼中經(jīng)常看到過這樣的代碼:
export default Vuex.Store({
state: () => ({ counter: 0 }),
getters: {
// 完全無用的 getter
getCount: state => state.counter,
},
})
這在 Vuex 中只是不必要的樣板代碼,在 Pinia 中也是如此。你可以直接訪問狀態(tài):
const counterStore = useCounterStore()
counterStore.counter // 0 ?
PS:大多數(shù)時候你不需要 storeToRefs()(或 toRef())。你可以直接使用 store,Vue 的響應(yīng)式真的很方便 ??。
2、在 Option Stores 中使用組合式函數(shù)
你可以在 option stores 中使用一些組合式函數(shù),特別是那些持有狀態(tài)且可寫的組合式函數(shù)。例如,你可以使用 @vueuse/core 的 useLocalStorage() 將一些狀態(tài)存儲在瀏覽器的本地存儲中。
import { useLocalStorage } from '@vueuse/core'
const useAuthStore = defineStore('auth', {
state: () => ({
user: useLocalStorage('pinia/user/login', 'alice'),
}),
})
或者使用 refDebounced() 對 ref 的更改進(jìn)行防抖處理:
import { refDebounced } from '@vueuse/core'
const useSearchStore = defineStore('search', {
state: () => ({
user: {
text: refDebounced(/* ... */),
},
}),
})
3、在 Setup Stores 中使用復(fù)雜的組合式函數(shù)
在 Setup stores 中,你可以使用任何你想要的組合式函數(shù)。你可以連接到 websocket、藍(lán)牙處理或甚至游戲手柄!
import { useWebSocket } from '@vueuse/core'
export const useServerInfoStore = defineStore('server-info', () => {
const { status, data, send, open, close } = useWebSocket('ws://websocketurl')
return {
status,
data,
send,
open,
close,
}
})
Pinia 會自動識別哪些是狀態(tài)、getter 或動作。記住,必須從 setup 函數(shù)返回所有狀態(tài)屬性。
在 setup stores 中使用 inject()
你可以在 setup stores 中使用 inject() 來訪問應(yīng)用級別提供的變量,如路由器實(shí)例:
import { useRouter } from 'vue-router'
export const useAuthStore('auth', () => {
const router = useRouter()
function logout() {
// 登出用戶
return router.push('/login')
}
return {
logout
}
})
使用嵌套 Stores 創(chuàng)建私有狀態(tài)
setup stores 的一個黃金規(guī)則是返回每一個狀態(tài)片段:
export const useAuthStore('auth', () => {
const user = ref<User | null>(null)
const token = ref<string | null>(null)
// 我們必須返回 user 和 token
return {
user,
token,
}
})
但如果我們想要隱藏一些 store 中的狀態(tài)怎么辦?我們可以創(chuàng)建一個包含私有狀態(tài)的嵌套 store:
export const usePrivateAuthState('auth-private', () => {
const token = ref<string | null>(null)
return {
token,
}
})
export const useAuthStore('auth', () => {
const user = ref<User | null>(null)
const privateState = usePrivateAuthState()
privateState.token // 僅在此 store 中可訪問
return {
user,
}
})
在 SSR 中使用僅客戶端狀態(tài)
服務(wù)器端渲染(SSR)是提高應(yīng)用性能的絕佳方式。然而,與僅客戶端應(yīng)用相比,它帶來了一些額外的困難。例如,你無法訪問 window、document 或任何其他特定于瀏覽器的 API,如本地存儲。
在 Option Stores 中,這要求你使用 hydrate 選項(xiàng)告訴 Pinia 某些狀態(tài)不應(yīng)在客戶端上進(jìn)行 hydrate:
import { useLocalStorage } from '@vueuse/core'
const useAuthStore = defineStore('auth', {
state: () => ({
user: useLocalStorage('pinia/user/login', 'alice'),
}),
hydrate(state, initialState) {
state.user = useLocalStorage('pinia/user/login', 'alice')
},
})
在 Setup Stores 中,你可以使用 skipHydrate 輔助函數(shù)標(biāo)記某些狀態(tài)為僅客戶端狀態(tài):
import { defineStore, skipHydrate } from 'pinia'
const useAuthStore = defineStore('auth', () => {
const user = skipHydrate(useLocalStorage('pinia/user/login', 'alice'))
return { user }
})
總結(jié)
當(dāng)然還有許多其他的技巧可以分享,但這些是我認(rèn)為比較有用的。此外,大多數(shù)人對它們并不了解。你有沒有發(fā)現(xiàn)任何有用的 Pinia 技巧或竅門?