0

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

假设我有一个user界面。

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

export default User;

store/modules/state.ts我调用 Type 并创建用户状态。

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的方式。但是,松果的正确方法是什么。此外,吸气剂和动作也是如此。应该如何导出和使用它们。

4

1 回答 1

1

根据官方Pinia 文档

Vuex 具有包含多个模块的单个商店的概念。这些模块可以选择命名空间,甚至可以相互嵌套。将该概念转换为与 Pinia 一起使用的最简单方法是,您以前使用的每个模块现在都是一个商店。

所以现在你应该将每个 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、动作和状态拆分为多个文件,可以在我提供的示例中讨论官方 repo 问题,这对我有用。这是一个链接

于 2021-12-25T14:07:51.547 回答