在 PINIA、Vue3+Typescript 上处理命名空间模块化方法

Handling namespaced modular approach on PINIA, Vue3+Typescript

通常我使用命名空间 vuex。但是我决定退出 vuex 因为 Pinia 有 vue 核心团队的支持。我认为这对未来的发展更好。现在,我正在使用模块化方法创建商店,但无法真正理解如何在打字稿项目中处理该部分。

假设我有一个 user 接口。

interface User {
  email: string,
  username: string,
}

export default User;

store/modules/state.ts 中,我正在调用类型并创建用户状态。

import User from "../../types/User"

export const state = () => {
  return {
    user: {} as User | null,
  };
}

store/modules/index.ts 中我应该导入状态。并制作 namespace: true 然后将其导出用于 pinia 存储的 defineStore()。

import {state} from "./state"

export default {
  namespace: true,
  state,
}

store/index.ts

import {defineStore} from "pinia"
import {data} from "./modules"

export const Store = defineStore(data)

上面好了,命名空间部分我用的是vuex的方式。但是什么是 pinia 的正确方法。此外,吸气剂和动作也是如此。应该如何导出和使用它们。

根据官方Pinia docs

Vuex has the concept of a single store with multiple modules. These modules can optionally be namespaced and even nested within each other. The easiest way to transition that concept to be used with Pinia is that each module you used previously is now a store.

所以现在您应该将每个 vuex 模块视为一个单独的 pinia 存储。查看您的示例,它可能看起来像这样。在 store/modules/index.ts 中创建文件并粘贴:

import { defineStore } from "pinia";
import state from "store/modules/state.ts"; // Assuming that it's path to user state

export const useUserStore = defineStore('some/vuex/module/name', {
  state: state,
  getters: {
    // your getters here, check the Offical Pinia above
  },
  actions: {
    // your actions and mutations here, also check the offical Pinia Docs
  }
})

如果您想将 getter、操作和状态拆分到多个文件中,可以在我提供示例的地方讨论官方回购问题,这对我有用。这是一个link