我很无助。。。。。
首先我说下,我登录的思路一定是有错误的地方。
我说下我的登录过程。是这样的我通过在stroe文件里写了一个mutations里面的方法login,用了axios访问登录的api,
这个登录api很直接,你传给的用户和密码和数据库中匹配上就返回{success:true}否则{succes:false},
关键是我的效果是这样的我解析后端返回的字段,然后把字段存在state里面,比如loginStatus,
我模拟一个登录过程
我输完账号密码,点击登录,然后请求后端,保存后端的数据,接着对现在的数据进行判断,true跳转路由,false提示用户你的密码错误。
但是axios是异步的,我真的很难受,我请求还没有返回信息,就进行下面的判断,我改这么写啊。。。。。难受啊
submitForm(formName) {
if (formName.username === ''){
// this.$message({
// message:"用户名是空的!",
// type:'warning'
// });
return false;
} else if (formName.password === ''){
// this.$message({
// message:"密码是空的!",
// type:'warning'
// });
return false;
}
this.$store.dispatch("checkLogin",formName)
if (this.$store.state.user_status === false){
this.$message.error("你的用户名或者密码错误!")
return false;
}
router.push("/index");
}
mutations: {
REGUSER (state,data) {
axios.post('/api/reguser',{
data
})
.then(function (repoomse) {
console.log(repoomse)
})
.catch(function (error) {
console.log(error)
})
},
LOGIN(state,data) {
axios.post('/api/login',{
data
})
.then(function (repo) {
if (repo.status === 200 && repo.data.success === "true") {
state.user_status = true
} else {
state.user_status = false
}
})
.catch(function (error) {
console.log(error)
})
}
},
actions: {
checkLogin({commit},data){
commit("LOGIN",data);
}
}
我的代码写的很烂。后端我用servlet写的,尽情喷和指点谢谢~
Vuex
最好是需要用到的时候,才考虑用。你这个似乎明显是为了强行使用,不考虑Vuex
的使用场景....dispatch
,这个是可以异步的。Promise
方案是可行的。并且官方也是这么推荐的。https://vuex.vuejs.org/zh/gui...
或者题主不想用
promise
的话,直接在action
里面跳转吧。。。