Search code examples
vuejs3vitepinia

Handling namespaced modular approach on PINIA, Vue3+Typescript


normally I was using namespaced vuex. But I am deciding to quit vuex because Pinia has the vue core team support. I think it's better for the future developements. Now I am creating store with a modular approach but couldn't really understand how to handle that part on typescript project.

let's say I have a user interface.

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

export default User;

and in store/modules/state.ts I am calling the Type and creating a user state.

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

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

and in store/modules/index.ts I should import the state. And make the namespace: true then export it for the defineStore() for pinia store.

import {state} from "./state"

export default {
  namespace: true,
  state,
}

in store/index.ts

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

export const Store = defineStore(data)

okay above, namespace part I use the vuex way. But what is the right approach for the pinia. Additionally, getters and actions as well. How should export and use them.


Solution

  • According to official 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.

    So now you should think about each vuex module as an separated pinia store. Looking at your example it could look like this. create file in store/modules/index.ts and paste:

    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
      }
    })
    

    If you want to split getters, actions and state into multiple files, there is discussion on offical repo issue where I provided example, that is working for me. Here is a link