怎么获取vuex中action中的返回值

vuex中,action调用接口使用.then方法返回值不能获取到,如下action:

 1 import {
 2     reqLogin
 3 } from '@/api/index'
 4 export default ({
 5     state: {
 6         token: '',
 7     },
 8     mutations: {
 9         Login(state, token) {
10             state.token = token
11         }
12     },
13     actions: {
14         reqLogin({
15             commit
16         }, datas = {}) {
17             reqLogin(datas).then((res)=>{
18                 if (res.code == 200) {
19                     commit("Login", res.data.token)
20                     return Promise.resolve(true)
21                 } else {
22                     return Promise.reject(false)
23                 }
24         })
25            
26         },
27     },
28     modules: {}
29 })    

要获取vuex中action中的返回值,其正确的是只用async 和await ,进行同步

actions: {
        async reqLogin({
            commit
        }, datas = {}) {
            let res = await reqLogin(datas)
            if (res.code == 200) {
                commit("Login", res.data.token)
                return Promise.resolve(true)
            } else {
                return Promise.reject(new Error(false))
            }
        }
    },

调用action方法,获取其返回值

methods: {
    // 方法一  (this.$store.dispatch与mapActions都可)
    login() {
      if (this.phone && this.pwd) {
        let reqData = { phone: this.phone, password: this.pwd };
        this.$store.dispatch("reqLogin", reqData).then((res) => {
            if (res) {
              console.log(res);
              this.$router.push("/home");
            }
          });
       }
    },
    //方法二
    async login1() {
      if (this.phone && this.pwd) {
        let reqData = { phone: this.phone, password: this.pwd };
        let res=await this.$store.dispatch("reqLogin", reqData)
          if (res) {
            console.log(res);
            this.$router.push("/home");
          }
       }
    },
}    

可参考官网中   组合action

https://vuex.vuejs.org/zh/guide/actions.html

 

posted @ 2022-01-10 16:31  阿piu~ต  阅读(2362)  评论(1编辑  收藏  举报