Pinia 組合式 Store

2023-09-28 15:29 更新

組合式 Store

組合式 store 是可以相互使用,Pinia 當(dāng)然也支持它。但有一個(gè)規(guī)則需要遵循:

如果兩個(gè)或更多的 store 相互使用,它們不可以通過(guò) gettersactions 創(chuàng)建一個(gè)無(wú)限循環(huán)。它們也不可以同時(shí)在它們的 setup 函數(shù)中直接互相讀取對(duì)方的 state:

  1. const useX = defineStore('x', () => {
  2. const y = useY()
  3. // ? 這是不可以的,因?yàn)?y 也試圖讀取 x.name
  4. y.name
  5. function doSomething() {
  6. // ? 讀取 computed 或 action 中的 y 屬性
  7. const yName = y.name
  8. // ...
  9. }
  10. return {
  11. name: ref('I am X'),
  12. }
  13. })
  14. const useY = defineStore('y', () => {
  15. const x = useX()
  16. // ? 這是不可以的,因?yàn)?x 也試圖讀取 y.name
  17. x.name
  18. function doSomething() {
  19. // ? 讀取 computed 或 action 中的 x 屬性
  20. const xName = x.name
  21. // ...
  22. }
  23. return {
  24. name: ref('I am Y'),
  25. }
  26. })

嵌套 store

注意,如果一個(gè) store 使用另一個(gè) store,你可以直接導(dǎo)入并在 actionsgetters 中調(diào)用 useStore() 函數(shù)。然后你就可以像在 Vue 組件中那樣使用 store。參考共享 Getter共享 Action。

對(duì)于 setup store ,你直接使用 store 函數(shù)頂部的一個(gè) store:

  1. import { useUserStore } from './user'
  2. export const useCartStore = defineStore('cart', () => {
  3. const user = useUserStore()
  4. const list = ref([])
  5. const summary = computed(() => {
  6. return `Hi ${user.name}, you have ${list.value.length} items in your cart. It costs ${price.value}.`
  7. })
  8. function purchase() {
  9. return apiPurchase(user.id, this.list)
  10. }
  11. return { summary, purchase }
  12. })

共享 Getter

你可以直接在一個(gè) getter 中調(diào)用 useOtherStore()

  1. import { defineStore } from 'pinia'
  2. import { useUserStore } from './user'
  3. export const useCartStore = defineStore('cart', {
  4. getters: {
  5. summary(state) {
  6. const user = useUserStore()
  7. return `Hi ${user.name}, you have ${state.list.length} items in your cart. It costs ${state.price}.`
  8. },
  9. },
  10. })

共享 Actions

actions 也一樣:

  1. import { defineStore } from 'pinia'
  2. import { useUserStore } from './user'
  3. export const useCartStore = defineStore('cart', {
  4. actions: {
  5. async orderCart() {
  6. const user = useUserStore()
  7. try {
  8. await apiOrderCart(user.token, this.items)
  9. // 其他 action
  10. this.emptyCart()
  11. } catch (err) {
  12. displayError(err)
  13. }
  14. },
  15. },
  16. })
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)