是否可以在导出的模块中使用 Vuex mapActions

Is it possible to use Vuex mapActions inside an exported module

是否可以从导入到组件中的单独模块调用 Vuex mapActions?

我正在尝试标准化 vue.js 网络应用程序中的一组功能。我想将它们导入到每个组件中,并传递一些值给函数操作。我正在使用 vuex 来管理状态。目前,每个组件在每次加载时都会调用这些函数(完全相同)。

我想将其重构为一个模块,并根据需要将其导入到每个组件中。此代码使用 mapActions 作为其功能的一部分。下面是相关的代码片段:component, module, vuex action

Vue 组件:

//the imported function call
if (!this.queued){
   timer.updatePage(this.pagination, this.orders);
}

模块代码(advance.js):

import { mapActions } from 'vuex';

let currentComp = {
   name: 'purchase',
   date: null,
   start: false
}

const timer = {
   ...mapActions(['currentComponent']),
   updatePage(pagination, order) {
      currentComp.name = 'nextComponent';
      this.currentComponent(currentComp);
   }
}
export default timer;

vuex代码:

//in the actions section:
currentComponent({
        commit
    }, comp) {
        console.log(comp);
        commit('setCurrentComponent', comp);
}

//in the mutations section:
setCurrentComponent: (state, comp) => {
        state.currentComponent = comp.name;
        return state;
    }

当组件运行导入的函数时,我得到:

vuex.esm.js?2f62:870 Uncaught TypeError: Cannot read property 'dispatch' of undefined
    at Object.mappedAction [as currentComponent] (vuex.esm.js?2f62:870)
    at eval (advance.js?935c:37)

当我从 this.currentComponent 中删除 this 时,我得到:

advance.js?935c:37 Uncaught ReferenceError: currentComponent is not defined
    at eval (advance.js?935c:37)

提前感谢您的指导。

mapActions 是创建类似这样的方法的快捷方式

currentComponent() {
   this.$store.dispatch('xxx')
}

调用此函数时,this 上下文为 timer。由于 timer 没有 $store 属性,您会得到错误 Cannot read property 'dispatch' of undefined。解决此问题的最快方法是将 this 上下文更改为具有 $store 属性 的组件。您可以通过将组件作为 updatePage 中的第三个 属性 传递并将 currentComponent 绑定到函数来实现。

// component code
timer.updatePage(this.pagination, this.orders, this);

// advance.js
const timer = {
   ...mapActions(['currentComponent']),
   updatePage(pagination, order, component) {
      currentComp.name = 'nextComponent';
      this.currentComponent.bind(component)(currentComp);
   }
}

不过,我建议对此类行为使用 mixin

import { mapActions } from 'vuex';

let currentComp = {
   name: 'purchase',
   date: null,
   start: false
}

const timerMixin = {
   methods: {
       ...mapActions(['currentComponent']),
       updatePage(pagination, order) {
          currentComp.name = 'nextComponent';
          this.currentComponent(currentComp);
       }
   }
}
export default timerMixin;

在您的组件中,导入 timerMixin 并将其注册为混入。这些方法将直接在您的组件上可用,您可以通过对现有代码进行一些小的调整来调用它们。

if (!this.queued){
   this.updatePage(this.pagination, this.orders);
}