用戶登錄和權限分配這塊還是挺繞的,自己目前還沒研究透徹,但是知道流程是這樣的
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" />
這樣就把擁有權限的菜單顯示出來了