在我的 Vuex 设置中,商店目前的结构如下:
store
- modules
- common_data
- index.js
- mutations.js
- actions.js
- getters.js
现在,actions.js
中的一个 Action 被定义为:
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 实例在这里不可用,这导致操作失败并出现错误:无法读取未定义的属性“get”
。我尝试了其他组合,例如 this.axios
和 vue.axios
但结果是一样的。
我做错了什么吗?处理此类情况的常见模式是什么?
最佳答案
如果不传递 Vue 实例或创建新实例,您将无法访问它。
做你想做的事情的一个简单方法是简单地将你的 this
传递给你的操作 this.$store.dispatch('populateTimeZones', this)
,然后将您的方法签名更改为 populateTimeZones({ context }, vueInstance)
。这将允许您访问 vueInstance.$http
。
另一个想法是 vue-inject这是 Vue 的 DI 容器。它允许您将 axios 注册为服务,然后在需要时只需调用 VueInjector.get('axios') 即可。在 Vue 组件本身上,您可以执行 dependencies: ['axios'] 然后使用 like this.axios。在这种情况下不是什么大问题,但当您有很多服务为您工作时很有帮助
关于vue.js - 在 Vuex 模块 Action 中访问 vue-axios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47246459/