Pinia 不使用 `setup()` 的用法

2023-09-28 15:28 更新

不使用 setup() 的用法usage-without-setup}

即使你沒有使用組合式 API,也可以使用 Pinia(如果你使用 Vue 2,你仍然需要安裝 @vue/composition-api 插件)。雖然我們推薦你試著學(xué)習(xí)一下組合式 API,但對你和你的團隊來說目前可能還不是時候,你可能正在遷移一個應(yīng)用,或者有其他原因。

給予整個 store 的訪問權(quán)

如果你需要訪問 store 里的大部分內(nèi)容,映射 store 的每一個屬性可能太麻煩。你可以試試用 mapStores() 來訪問整個 store:

  1. import { mapStores } from 'pinia'
  2. // 給出具有以下 id 的兩個 store
  3. const useUserStore = defineStore('user', {
  4. // ...
  5. })
  6. const useCartStore = defineStore('cart', {
  7. // ...
  8. })
  9. export default {
  10. computed: {
  11. // 注意,我們不是在傳遞一個數(shù)組,而是一個接一個的 store。
  12. // 可以 id+'Store' 的形式訪問每個 store 。
  13. ...mapStores(useCartStore, useUserStore)
  14. },
  15. methods: {
  16. async buyStuff() {
  17. // 可以在任何地方使用他們!
  18. if (this.userStore.isAuthenticated()) {
  19. await this.cartStore.buy()
  20. this.$router.push('/purchased')
  21. }
  22. },
  23. },
  24. }

默認情況下,Pinia 會在每個 store 的 id 后面加上 "Store" 的后綴。你可以通過調(diào)用 setMapStoreSuffix() 來自定義:

  1. import { createPinia, setMapStoreSuffix } from 'pinia'
  2. // 完全刪除后綴:this.user, this.cart
  3. setMapStoreSuffix('')
  4. // this.user_store, this.cart_store (沒關(guān)系,我不會批評你的)
  5. setMapStoreSuffix('_store')
  6. export const pinia = createPinia()

TypeScript

默認情況下,所有映射輔助函數(shù)都支持自動補全,你不需要做任何事情。如果你調(diào)用 setMapStoreSuffix() 修改了 "Store" 的后綴,你還需要在 TS 文件或 global.d.ts 文件的某個地方添加它。最方便的地方就是你調(diào)用 setMapStoreSuffix() 的地方:

  1. import { createPinia, setMapStoreSuffix } from 'pinia'
  2. setMapStoreSuffix('') // 完全刪除后綴
  3. export const pinia = createPinia()
  4. declare module 'pinia' {
  5. export interface MapStoresCustomization {
  6. // 設(shè)置成和上面一樣的值
  7. suffix: ''
  8. }
  9. }

如果你使用的是 TypeScript 聲明文件(如 global.d.ts),請確保在文件頂部 import 'pinia',以暴露所有現(xiàn)有類型。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號