【问题标题】:Handling namespaced modular approach on PINIA, Vue3+Typescript在 PINIA、Vue 3+Typescript 上处理命名空间模块化方法
【发布时间】:2022-01-17 09:56:11
【问题描述】:

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

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

【问题讨论】:

    标签: vuejs3 vite pinia


    【解决方案1】:

    据官方Pinia docs

    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 问题,这对我有用。这是link

    【讨论】:

    • 感谢您通过链接指出基于模块的导入。我明白其中的逻辑。
    猜你喜欢
    • 2021-05-31
    • 2019-04-30
    • 2020-03-30
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 2017-07-15
    相关资源
    最近更新 更多