从 Vuex 模块中调用时,如何全局别名 Vuex Actions?

How to alias Vuex Actions globally, when called from within a Vuex module?

我本质上是在寻找 Vue 2 中的正确语法来创建可以全局访问但位于模块内的 Vuex 方法。我通常看到的约定使用 $ 字符,例如 $axios$store.

在实例化 Vue 实例时,我可以做一些事情,比如导入 Axios,然后像这样应用实例:

import Vue from 'vue';
import axios from 'axios';

export default (state) => {
    Vue.prototype.$axios = axios;
}

我想做的与此类似,但我想访问我创建的自定义 Vuex 模块。假设我的模块具有处理身份验证的操作,并且该模块名为 auth。假设这些操作之一是 logout 操作。我可以像这样在我的 Vue 组件中调用此操作:

this.$store.dispatch("auth/logout");

但是我希望能够简单地做到这一点而不是这个

this.$auth.logout()

或类似简洁的内容。

似乎不​​可能简单地做类似

的事情
import Vue from 'vue';

export default (state) => {
    Vue.prototype.$auth.logout = state.store.dispatch("auth/LOGOUT");
}

如何做到这一点?

你可以这样做:

// src/plugins/auth.js
import Vue from "vue";
import store from "../store";

Vue.prototype.$auth = {
  login() {
    store.dispatch("auth/LOGIN");
  },
  logout() {
    store.dispatch("auth/LOGOUT");
  }
};

并且在您的 main.js 中只需将导入添加到此文件中:

// src/main.js
// imports...
import "./plugins/auth.js";
// code...

你可以这样使用它:

// src/components/Test.vue
<script>
export default {
  created() {
    this.$auth.login()
  }
}
</script>

示例源代码:https://codesandbox.io/s/vuex-store-forked-pl01u