在我的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.axios
和,vue.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这样使用。在这种情况下,这并不是什么大问题,但在您有大量服务为您工作时会很有帮助
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句