【问题标题】:How do I get multiple actions and state with Vuex namespaced modules and the Vue Composition API?如何使用 Vuex 命名空间模块和 Vue 组合 API 获取多个操作和状态?
【发布时间】:2023-03-04 03:22:01
【问题描述】:

使用 Vue Options API,我可以通过以下方式获取操作和状态:

  computed: {
    ...mapState("myStore", ["myState", "myOtherState"]),
  },
  methods: {
    ...mapActions("myStore", ["myAction", "myOtherAction"]),
  }

我的问题是如何使用 Vuex 和 Vue Composition API 获得多个命名空间的操作和状态? 现在我有一个名为 useStoreModule.js 的包装器,看起来像这样:

import { createNamespacedHelpers } from "vuex-composition-helpers/dist";

export default function () {
  function getState(module, name) {
    const { useState } = createNamespacedHelpers(module);
    return useState([name]);
  }
  function getAction(module, name) {
    const { useActions } = createNamespacedHelpers(module);
    return useActions([name]);
  }
  return {
    getState,
    getAction,
  };
}

并通过以下方式获取状态/操作:

setup() {
    const { getState } = useStoreModule();
    const { myState } = getState("myStore", "myState");
}

那么我该如何编写包装器来做到这一点:

setup() {
    const { getState } = useStoreModule();
    const { myState, myOtherState, myOtherOtherState } = getState("myStore", ["myState", "myOtherState", "myOtherOtherState"]);
}

任何帮助表示赞赏:)

【问题讨论】:

    标签: javascript vue.js vuex vue-composition-api


    【解决方案1】:

    这是一种方法:

    component.vue

      import { getCurrentInstance } from 'vue';
    
      setup() {
        const _instance = getCurrentInstance();
        const { $store } = _instance.appContext.app.config.globalProperties;
      },
    

    createStore

    "use strict";
    import { createStore } from 'vuex';
    
    // Stores
    import moduleA from '@/store/moduleA.js';
    import moduleB from '@/store/moduleB.js';
    
    export const store = createStore({
      strict: true,
      modules: {
        moduleA,
        moduleB,
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2018-10-29
      • 2020-07-14
      • 2020-01-20
      • 2018-05-02
      • 2019-03-22
      • 1970-01-01
      • 2020-03-13
      • 2021-02-17
      • 1970-01-01
      相关资源
      最近更新 更多