Vuex modules

How to create vuex modules

Sat Jun 19 2021

So far We have been using props to pass data through parent child chain in our vuejs apps. This can be still working, we can do these data transactions and state management in a much easier way.

This is tutorial uses Typescript

Vuex Store Modules

Vuex store can be organized as modules, so that we can organize the data in a better way.Each module has its own state, mutations, actions and getters. Each state should have a type.

Products Module and interfaces

First up all create types for our state. The state is a indented to store values (array), so we have to define two types, one for state variable and another for array type.

export interface productState {
    products: Product\[\];
}

export interface Product {
    id: number;
    product: string;
    pk: string;
    mfr: string;
    hsn?: string;
    ts: number;
} 

export interface productState { products: Product[]; }

export interface Product { id: number; product: string; pk: string; mfr: string; hsn?: string; ts: number; }

import {productState} from '../types'
const state: productState={
products: \[{id:101,product:'SR TAB',mfr:'LAB',pk:'10s',ts:12},
{ id: 102, product: 'CIPLA DINE TUBE', mfr: 'CIPLA', pk: '1ml', ts: 18,hsn:'2003' },
{ id: 103, product: 'CIPLA TONE', mfr: 'CIPLA', pk: '200gm', ts: 12, hsn: '2004' },
\]
} 
const getters={
    products(state: productState){
       return state.products;
    }
}
export const productMaster= {
    namespaced: true,
    state,
    getters
}

Using the type ProductState we store the state and have one getter function for accessing the state variable.

Import the modules

In our main store file (index) we have to import the module as follows.

import {productMaster} from './productMaster'
....

  const Store = new Vuex.Store({
    modules: {
       productMaster
    },

How to invoke getters

To call the getter functions in a component/psge, we have to specify the module name and then the getter name.

this.$store.getters['productMaster/products'];

The above statement will invoke the product getter in the module productMaster. We can create as many module our app required.

Comments