# 组合 Stores
组合stores
是为了让store
间相互使用,并要遵循下面一些规则:
如果两个或多个store
相互使用,它们不能通过getters
或actions
创建无限循环。也不能在它们设置的函数中直接读取彼此的状态:
const useX = defineStore('x', () => {
const y = useY()
// ❌ This is not possible because y also tries to read x.name
y.name
function doSomething() {
// ✅ Read y properties in computed or actions
const yName = y.name
// ...
}
return {
name: ref('I am X'),
}
})
const useY = defineStore('y', () => {
const x = useX()
// ❌ This is not possible because x also tries to read y.name
x.name
function doSomething() {
// ✅ Read x properties in computed or actions
const xName = x.name
// ...
}
return {
name: ref('I am Y'),
}
})
# 嵌套 Stores
注意,如果一个store
使用了另一个store
,则无需在单独的文件中创建新的store
,您可以直接引入它。把它想象成嵌套。
您可以在任何getter
或action
的顶部调用useOtherStore()
:
import { useUserStore } from './user'
export const cartStore = defineStore('cart', {
getters: {
// ... other getters
summary(state) {
const user = useUserStore()
return `Hi ${user.name}, you have ${state.list.length} items in your cart. It costs ${state.price}.`
},
},
actions: {
purchase() {
const user = useUserStore()
return apiPurchase(user.id, this.list)
},
},
})
# 共享 Getters
您可以在getter
的内部直接调用 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
这同样适用于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)
}
},
},
})