组合 Stores

组合stores是为了让store间相互使用,并要遵循下面一些规则:

如果两个或多个store相互使用,它们不能通过gettersactions创建无限循环。也不能在它们设置的函数中直接读取彼此的状态:

  1. const useX = defineStore('x', () => {
  2. const y = useY()
  3. // ❌ This is not possible because y also tries to read x.name
  4. y.name
  5. function doSomething() {
  6. // ✅ Read y properties in computed or actions
  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. // ❌ This is not possible because x also tries to read y.name
  17. x.name
  18. function doSomething() {
  19. // ✅ Read x properties in computed or actions
  20. const xName = x.name
  21. // ...
  22. }
  23. return {
  24. name: ref('I am Y'),
  25. }
  26. })

嵌套 Stores

注意,如果一个store使用了另一个store,则无需在单独的文件中创建新的store,您可以直接引入它。把它想象成嵌套。

您可以在任何getteraction的顶部调用useOtherStore()

  1. import { useUserStore } from './user'
  2. export const cartStore = defineStore('cart', {
  3. getters: {
  4. // ... other 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: {
  11. purchase() {
  12. const user = useUserStore()
  13. return apiPurchase(user.id, this.list)
  14. },
  15. },
  16. })

共享 Getters

您可以在getter的内部直接调用 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. // another action
  10. this.emptyCart()
  11. } catch (err) {
  12. displayError(err)
  13. }
  14. },
  15. },
  16. })