【问题标题】:NuxtJS Vuex Module namespacing and mutations enumNuxtJS Vuex 模块命名空间和突变枚举
【发布时间】:2021-10-15 15:52:59
【问题描述】:

我有一个带有 Vuex 商店的 NuxtJS 网站。我有一个根状态和一个位于 store/shop/cart/state.ts 的模块,其 store/shop/cart/mutations.ts 文件看起来像这样。

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;

在我的middlewares 中,我想像这样提交突变。

store.commit(CartMutations.SET_CART, cart);

但是,由于命名空间,该操作被命名为shop/cart/SET_CART。所以我必须这样做,这不是最好的,因为我不能使用我的枚举。

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

有人也遇到过这种情况吗?我想知道一个干净的解决方案来解决这个问题,同时保留命名空间。

【问题讨论】:

    标签: typescript vue.js nuxt.js vuex


    【解决方案1】:

    这就是mapMutations() 派上用场的地方。

    看看这个namespace binding explanation on official Vue doc

    所以在这种情况下我会做的是

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

    【讨论】:

    • 我没有使用 mapMutations,因为我的使用仅用于单个突变,而不是在我的 components 中,而是在 middleware 文件夹中
    • IMO 最终要做的是在 store/shop/cart/state.ts 中定义这个 export const CART_MODULE = 'shop/cart'。并使用它为store.commit 加上前缀,例如store.commit(${CART_MODULE}${DistributorConfigMutations.SET_CART}, cart)
    猜你喜欢
    • 2013-04-13
    • 2023-03-30
    • 2020-07-14
    • 1970-01-01
    • 2018-03-26
    • 2020-05-07
    • 2023-03-19
    • 1970-01-01
    • 2017-10-13
    相关资源
    最近更新 更多