vue登录问题

我很无助。。。。。
首先我说下,我登录的思路一定是有错误的地方。
我说下我的登录过程。是这样的我通过在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写的,尽情喷和指点谢谢~

阅读 4k
4 个回答
  1. Vuex最好是需要用到的时候,才考虑用。你这个似乎明显是为了强行使用,不考虑Vuex的使用场景....
  2. 更新 ,刚没注意 你写的是dispatch ,这个是可以异步的。
  3. 楼上的Promise方案是可行的。并且官方也是这么推荐的。
    https://vuex.vuejs.org/zh/gui...
actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}

store.dispatch('actionA').then(() => {
  // ...
})

或者题主不想用promise的话,直接在action里面跳转吧。。。

async and await

可以让你的LOGIN写在Action里并且返回一个promise,然后这里就可以这么写(大概长这样):

this.$store.dispatch("checkLogin",formName).then(() => {
    if (this.$store.state.user_status === false){
      this.$message.error("你的用户名或者密码错误!")
      return false;
    }
}

把判断写在axios的.then()里面呢

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题