Composing Stores
组合商店是关于让商店相互使用,这在 Pinia 中得到了支持。 有一条规则要遵循:
如果两个或多个商店相互使用,它们就无法通过 getters 或 actions 创建无限循环。 他们不能两者在他们的设置函数中直接读取彼此的状态:
js
const useX = defineStore('x', () => {
const y = useY()
// ❌ 这是不可能的,因为 y 也尝试读取 x.name
y.name
function doSomething() {
// ✅ 在计算或动作中读取 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() {
// ✅ 在计算或动作中读取 x 属性
const xName = x.name
// ...
}
return {
name: ref('I am Y'),
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Nested Stores
请注意,如果一个商店使用另一个商店,您可以直接导入并调用_actions_和_getters_中的useStore()
函数。 然后,您可以像在 Vue 组件中一样与商店进行交互。 请参阅 共享获取器 和 共享操作。
当涉及到 setup stores 时,您可以简单地使用 store 函数的 **at top ** 之一:
ts
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 }
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Shared Getters
You can simply call useOtherStore()
inside a getter:
js
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}.`
},
},
})
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
Shared Actions
这同样适用于 actions:
js
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)
}
},
},
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18