用户登录和权限分配这块还是挺绕的,自己目前还没研究透彻,但是知道流程是这样的
1. 登录流程
首先在登录页面,点击登录按钮,调用handleLogin方法
handleLogin() {
this.$refs.loginForm.validate(valid => {
if (valid) {
this.loading = true
this.$store.dispatch('user/login', this.loginForm)
.then(() => {
this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
this.loading = false
})
.catch(() => {
this.loading = false
})
} else {
console.log('error submit!!')
return false
}
})
},
然后会调用mock/user.js中的user/login api接口,执行成功后,会调用全局状态管理中src/store/modules/user.js的login,把token信息存入cookie, 这样就登录成功了,然后转向首页
login({ commit }, userInfo) {
const { username, password } = userInfo
console.log('登录login')
console.log(userInfo)
return new Promise((resolve, reject) => {
login({ username: username.trim(), password: password }).then(response => {
const { data } = response
commit('SET_TOKEN', data.token)
setToken(data.token)
resolve()
}).catch(error => {
reject(error)
})
})
},
2.权限判断
用户登录成功后,会在全局钩子(src/permission.js)中router.beforeEach中进行拦截,读取cookie,判断用户是否拥有角色
router.beforeEach(async(to, from, next) => {
// start progress bar
NProgress.start()
// set page title
document.title = getPageTitle(to.meta.title)
console.log('开始拦截')
// determine whether the user has logged in
const hasToken = getToken()
if (hasToken) {
if (to.path === '/login') {
// if is logged in, redirect to the home page
next({ path: '/' })
NProgress.done()
} else {
// determine whether the user has obtained his permission roles through getInfo
const hasRoles = store.getters.roles && store.getters.roles.length > 0
if (hasRoles) {
next()
} else {
try {
// get user info
// note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
const { roles } = await store.dispatch('user/getInfo')
// 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?redirect=${to.path}`)
NProgress.done()
}
}
}
} else {
/* 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()
}
}
})
然后会在src/store/modules/permission.js中添加路由,然后在侧边栏src\layout\components\Sidebar\index.vue 中读取路由
<sidebar-item v-for="route in permission_routes" :key="route.path" :item="route" :base-path="route.path" />
这样就把拥有权限的菜单显示出来了