1.首先,点击登录按钮,触发handleLogin方法,通过 this.$store.dispatch(“user/login”, this.loginForm)调用vuex中login方法,此处user/login表示的是调用user文件下的login方法

 handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("user/login", this.loginForm)
            .then((v) => {
              this.$router.push({
                path: this.redirect || "/dashboard",
                query: this.otherQuery,
              });
              // this.loading = false;
            })
            .catch((e) => {
              // console.log(e);
              this.loading = false;
              if (e.response) {
                this.$message.closeAll();
                this.$message.warning("账号或者密码输入有误");
              }
            });
        } else {
          this.loading = false;
          console.log("error submit!!");
          return false;
        }
      });
    },

2.追踪到user文件下的login方法,开始登录,在login方法中commit mutation中的SET_TOKEN,把后端返回的sessionId作为参数传入。接下来看下mutation的SET_TOKEN

login({ commit }, userInfo) {
    const { username, password, tenant } = userInfo;

    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password, tenant })
        .then(response => {
          console.log(response,'login-res');
          commit("SET_TOKEN", response.sessionId);
          setToken(response.sessionId);//把sessionId存入cookie,每次请求都要携带
          
          // Cookies.set("Authorization", "Bearer " + response.access_token);
          resolve();
        })
        .catch(error => {
          // console.log(error);
          reject(error);
        });
    });
  }, 
export function setToken(token) {
  return Cookies.set(TokenKey, token)
}

3.追踪到mutation下的SET_TOKEN,把传入的sessionId保存到state

SET_TOKEN: (state, token) => {
    state.token = token
  },

4.登录成功后,跳转到首页,路由跳转需要通过路由守卫判断是否登录,逻辑为
检查是否有token
1.1若有,则判断跳转的路由是否是登录页面
1.1.1若是,直接放行
1.1.2若不是,判断vuex里是否保存了当前账号的角色
1.1.2.1若有,直接放行
1.1.2.2若没有,则分别调用getUserInfo()、getInfo()、generateRoutes分别获取当 前账号的用户信息,角色信息,菜单数据等,并存入vuex
1.2若没有,强制跳转到登录页面
router.beforeEach(async(to, from, next) => {
// start progress bar
NProgress.start()

// set page title
document.title = getPageTitle(to.meta.title)

// determine whether the user has logged in
const hasToken = getToken()//获取token

//判断是否有token
if (hasToken) {
//若有,则判断是否跳转到登录
if (to.path === ‘/login’) {//若是跳转到登录,直接放行
// if is logged in, redirect to the home page
next({ path: ‘/’ })
NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
} else {//若不是跳转到登录,则需要判断当前账号的角色
// determine whether the user has obtained his permission roles through getInfo
const hasRoles = store.getters.roles && store.getters.roles.length > 0
console.log(store.getters.roles)
if (hasRoles) {//若vuex里已经保存了当前帐号的角色信息(所以在角色权限页面中保存了角色信息后,并没有把角色信息存入vuex,需要重新登录)
next()//直接放行
} else {//若vuex没有当前账号的角色信息
try {
// get info
// note: roles must be a object array! such as: [‘admin’] or ,[‘developer’,‘editor’]
const roles = await store.dispatch(‘user/getInfo’)//获取角色信息

      //get userInfo
      const userInfo = await store.dispatch('user/getuserInfo');//获取用户信息(用户名,电话等信息)
      // generate accessible routes map based on roles
      const accessRoutes = await store.dispatch('permission/generateRoutes', roles)//获取页面菜单信息

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)//动态添加路由
      // hack method to ensure that addRoutes is complete
      // set the replace: true, so the navigation will not leave a history record
      next({ ...to, replace: true })
    } catch (error) {
      // remove token and go to login page to re-login
      await store.dispatch('user/resetToken')
      Message.error(error || 'Has Error')
      next(`/login`)
      NProgress.done()
    }
  }
}

} else {//没有token的话强制跳到登录页面
/* has no token*/
if (whiteList.indexOf(to.path) !== -1) {
// in the free login whitelist, go directly
next()
} else {
// other pages that do not have permission to access are redirected to the login page.
next(/login)
// ?redirect=${to.path}
NProgress.done()
}
}
})

同理,退出登录的时候需要在state以及cookie中移除token

Logo

前往低代码交流专区

更多推荐