在 Vuex 模块动作中访问 vue-axios

Accessing vue-axios inside Vuex module actions

在我的 Vuex 设置中,商店当前的结构如下:

store
 - modules
   - common_data
     - index.js
     - mutations.js 
     - actions.js 
     - getters.js

现在,actions.js 中的一项操作定义为:

populateTimeZones(context) {
    var baseUrl = context.getters.getApiBaseUrl;

    this.$http.get(baseUrl + '/time-zones')
    .then(function (res){
        if(res.status == 'ok'){
            this.$store.commit('SET_TIME_ZONES', res.info.timeZones);
        } else {
            alert('An error occurred. Please try again!');
            return;
        }
    }.bind(this));
}

我认为 Vue 实例在这里不可用,这导致操作失败并显示错误:Cannot read property 'get' of undefined。我尝试了其他组合,例如 this.axiosvue.axios,但结果是一样的。

我是不是做错了什么?处理此类情况的常见模式是什么?

如果不传递 Vue 实例或创建新实例,您将无法访问它。

做你想做的事情的一个简单方法是简单地将你的 this 传递给你的操作 this.$store.dispatch('populateTimeZones', this),然后将你的方法签名更改为 populateTimeZones({ context }, vueInstance)。这将允许您访问 vueInstance.$http.

另一个想法是 vue-inject,它是 Vue 的 DI 容器。它允许您将 axios 注册为服务,然后在需要时只需调用 VueInjector.get('axios') 即可。在 Vue 组件本身上,您可以执行依赖项:['axios'] 然后像 this.axios 一样使用。在这种情况下不是什么大问题,但当您有很多服务为您工作时很有帮助