首页 > 解决方案 > 登录方法在推送路由之前不等待调度动作完成

问题描述

在我的组件 UserLogin 中,有一个调用此方法的提交按钮:

    methods: {
        login() {
          this.$store
            .dispatch("login", {
              email: this.email,
              password: this.password
            })
            //then redirect to default app
            .then(() => {
              console.log("2: router push to main")
              this.$router.push({ name: "main" })
            })
            //error handeling
            .catch(err => {
              this.error = err.response.data.error
            })
        }
      }

发送的登录操作在我的商店模块 user.js 中

     actions: {
            login({
                commit
            }, credentials) {
                ChatService.userLogin(credentials)
                    .then(response => {
                        commit('SET_USER_DATA', response)
                        console.log('1 : login dispatch')
                    })
                    .catch(error => {
                        console.log('Error login:', error)
                    })
            }
        },

Chatservice 是一个 axios api:

    import axios from 'axios'
    import store from "../../store/store"

    let apiClient = axios.create({
        baseURL: `http://127.0.0.1:8080/`,
        withCredentials: false, 
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json'
        }
    }) 

//The interceptor write the server token in Authorization header

    apiClient.interceptors.request.use(function (config) {
        const token = store.getters.token;
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
            console.log(token)
        }
        return config;
    }, function (err) {
        return Promise.reject(err);
    });

    export default {
        // USER AUTHENTICATION
        userLogin(credentials) {
            return apiClient.post('/login', credentials)
        }

我的问题是当我按下提交按钮时,上面的 2 个控制台日志按此顺序调用:

2:路由器推送到主服务器 1:登录调度

这意味着我的方法中的 .then 在操作完成之前被调用。这是一个大问题,因为它会在我设置 userData 信息之前尝试推送路由......

我怎样才能改变这种行为?非常感谢

标签: vue.jsaxiosvuexvue-router

解决方案


你可以试试这个。如下所示推动路线

actions: {
            login({
                commit
            }, credentials) {
                ChatService.userLogin(credentials)
                    .then(response => {
                        commit('SET_USER_DATA', response)
                        console.log('1 : login dispatch')
                        this.$router.push({ name: "main" })
                    })
                    .catch(error => {
                        console.log('Error login:', error)
                    })
            }
        },

您的登录方法只会调度操作,而操作将返回承诺..


推荐阅读