如何在vuex动作对象中编写异步代码?

时间:2019-02-10 16:14:07

标签: vue.js vuex

我的vue.js应用程序具有Rest api,并且想知道是否还有其他方法可以使用vuex编写异步代码?

我的代码如下

//store.js

const actions = {
    async GET_CLAN_MEMBERS({commit},id){
        let token = users.getters.getToken;
        return await axios.post(config.api + 'clans/' + id,{token})
    }
};

//Component.vue

created (){       
   this.$store.dispatch('GET_CLAN_MEMBERS',this.$route.params.id).then((res) => 
   {
      this.members = res.data;
   })
},

现在它可以工作了,但我不知道它是最好的地方,还是练习将它写在store.js文件中。
提前致谢。

2 个答案:

答案 0 :(得分:1)

标准做法:动作始终用作setter,因此在api回调响应后,您应调用mutation以根据响应数据更改状态,并将getter用作getter(状态数据检索)

因此,您应遵循以下流程图进行标准操作:

enter image description here

有关更多信息,请阅读here

答案 1 :(得分:0)

我也是,这个问题困扰了我,实际上商店可以在其操作中消耗其余api。

这就是vuex支持modules以避免存储太大文件的原因。

我做了一些实验here(省略了模块化,但是作为一个很好的例子),the official documentation itself说在动作内部调用异步操作。因此,推荐使用axios / rest inside动作。