NuxtJS Vuex Module namespacing and mutations enum

Viewed 89

I have a NuxtJS website with a Vuex store. I have a root state and a module located at store/shop/cart/state.ts with a store/shop/cart/mutations.ts file looking like this.

import { MutationTree } from 'vuex';
import { CartState } from './state';
import { Cart } from '~/types/Cart';

export enum CartMutations {
  SET_CART = 'SET_CART',
}

const mutations: MutationTree<CartState> = {
  [CartMutations.SET_CART](
    state: CartState,
    payload: { cart: Cart }
  ) {
    state.cart = payload.cart;
  },
};

export default mutations;

Inside my middlewares, I would like to commit the mutation like so.

store.commit(CartMutations.SET_CART, cart);

However, due to namespacing, the action is named shop/cart/SET_CART. So I would have to do this which is not the best since I cannot use my enum.

store.commit('shop/cart/SET_CART', cart);

Did someone run into this as well ? I'm wondering about a clean solution to workaround this while keeping the namespaces.

1 Answers

this is where mapMutations() comes handy.

check out this namespace binding explanation on official Vue doc.

so what I would do in this case is

// inside constant declaration file
export const SHOP_CART_STORE = 'shop/cart';

// inside component
import {SET_CART} from 'CartStore';

{
  methods: {
    ...mapMutations(SHOP_CART_STORE, {setCart: SET_CART}),
    doTheJob(cart) {
      this.setCart(cart);
    }
  }
}
Related