IView-admin——Login的流程逻辑

1.1、点击登陆按钮触发handleSubmit方法

// @/view/login/login.vue
    handleSubmit ({ userName, password }) {
      this.handleLogin({ userName, password }).then(res => {
        this.getUserInfo().then(res => {
          this.$router.push({
            name: this.$config.homeName
          })
        })
      })
    }

2.1、上述第二行触发handleLogin方法,此方法返回一个Promise

// @/store/module/user.js
    handleLogin({ commit }, { userName, password }) {
      userName = userName.trim()
      return new Promise((resolve, reject) => {
        login({
          userName,
          password
        }).then(res => {
          const data = res.data
          commit('setToken', data.token)
          resolve()
        }).catch(err => {
          reject(err)
        })
      })

3、上述的Promise触发了login方法,此方法发送了一个post请求,并将数据返回。

// @/api/user.js
export const login = ({ userName, password }) => {
  const data = {
    userName,
    password
  }
  return axios.request({
    url: 'login',
    data,
    method: 'post'
  })
}

4、因为发送了请求,所以Mock开始拦截并模拟返回数据。

// 返回数据格式
{
  status: 200,
  data: // 就是拦截函数的返回值
}
export const login = req => {
  req = JSON.parse(req.body)
  if (USER_MAP[req.userName] && USER_MAP[req.userName].password === req.password) {
    return {
      token: USER_MAP[req.userName].token
    }
  } else {
    return false
  }
}

2.2、得到返回数据后继续跳回2.1的函数,成功发送请求并得到数据就进入到下一个then中执行函数。即

then(res => {
  const data = res.data
  commit('setToken', data.token)
  resolve()
})

1.2、因为上述then方法执行了resolve(),所以进行到下一个then方法中执行函数,就跳回1函数。即

then(res => {
  this.getUserInfo().then(res => {
    this.$router.push({
      name: this.$config.homeName
    })
  })
})

然后执行getUserInfo方法——跳转页面。

Logo

前往低代码交流专区

更多推荐