vue.js - 登录方法在推送路由之前不等待调度动作完成
问题描述
在我的组件 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 信息之前尝试推送路由......
我怎样才能改变这种行为?非常感谢
解决方案
你可以试试这个。如下所示推动路线
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)
})
}
},
您的登录方法只会调度操作,而操作将返回承诺..
推荐阅读
- python - Selenium 关闭/接受 Chrome 确认弹出窗口
- javascript - Javascript/Jquery:按顺序执行相同或不同的函数
- javascript - 无法读取未定义的属性“parentNode”(谷歌标签管理器,f.parentNode.insertBefore(j,f))
- sql-server - 将日期与特定日期格式进行比较
- c# - 通过 ICollectionView 过滤 ObservableCollection 并使用它
- docker - 无法按名称访问虚拟主机域 docker apache - 一个灯堆栈应用程序
- react-native - polidea ble编码发送包到base64
- javascript - 提供的注册令牌未注册。以前有效的注册令牌可能由于多种原因而被注销
- php - 为什么 isPasswordValid() 函数总是返回 false?
- python - Plotly:如何在不同的轨迹上绘制带有时间值的标记?