组合 Store
组合 Store 是指让 Store 相互使用,这在 Pinia 中得到了支持。如果一个 Store 使用另一个 Store,假设名称useUserStore,您可以直接import
它,然后useUserStore(),再然后在actions或getters中,使用它。像在 Vue 组件中一样,与 Store 进行交互。
import { useUserStore } from './user' export const useCartStore = defineStore('cart', () => { const user = useUserStore() const summary = computed(() => { return `Hi ${user.name}, you have ${state.list.length} items in your cart. It costs ${state.price}.` }) function purchase() { return apiPurchase(user.id, this.list) } return { summary, purchase } })
如果两个或多个 Store 相互使用,有一条规则要遵循:不能通过getters或actions创建无限循环;不能在setup()
函数中,直接读取彼此的state。
const useX = defineStore('x', () => { const y = useY() // ❌ 这是不可以的,因为 y 也试图读取 x.name y.name function doSomething() { // ✅ 取 computed 或 action 中的 y 属性const yName = y.name // ... } return { name: ref('I am X'), } }) const useY = defineStore('y', () => { const x = useX() // ❌ 这是不可以的,因为 x 也试图读取 y.name x.name function doSomething() { // ✅ 读取 computed 或 action 中的 x 属性const xName = x.name // ... } return { name: ref('I am Y'), } })
共享 getters
您可以简单地在getters内部中,简单调用useOtherStore():
import { defineStore } from 'pinia' import { useUserStore } from './user' export const useCartStore = defineStore('cart', { getters: { summary(state) { const user = useUserStore() return `Hi ${user.name}, you have ${state.list.length} items in your cart. It costs ${state.price}.` }, }, })
共享 actions
import { defineStore } from 'pinia' import { useUserStore } from './user' export const useCartStore = defineStore('cart', { actions: { async orderCart() { const user = useUserStore() try { await apiOrderCart(user.token, this.items) // another action this.emptyCart() } catch (err) { displayError(err) } }, }, })