创建permission.js文件,内容如下
// 路由守卫
import router from './router'
import user from './api/user'
import store from './store'
// 白名单
const whiteList = ['/login', '/register']
router.beforeEach((to, from, next) => {
if (localStorage.getItem('Token')) {
if (to.path === '/login') {
next({
path: '/'
})
} else {
//这一块代码根据自己的业务是做的
Promise.all([user.getUserInfo()]).then(res => {
// console.log('wwwwee')
console.log(res)
store.commit('user/SET_IMG', res[0].data.img)
store.commit('user/SET_USERID', res[0].data.id)
store.commit('user/SET_NACKNAME', res[0].data.nackname)
store.commit('user/SET_ADDRESS', res[0].data.address)
store.commit('user/SET_AGE', res[0].data.age)
store.commit('user/SET_SEX', res[0].data.sex)
store.commit('user/SET_EMAIL', res[0].data.email)
store.commit('user/SET_ROLE', res[0].data.role)
next()
})
// Promise.all([
// api.common.getOrganizations(),
// api.common.getCategories(),
// api.user.getUserInfo()
// ])
// .then(res => {
// // 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation
// // 要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法
// store.commit('common/SET_ORGANIZATIONS', res[0])
// store.commit('common/SET_CATEGORIES', res[1])
// store.commit('user/SET_USERID', res[2].user_id)
// store.commit('user/SET_USERNAME', res[2].user_name)
// store.commit('user/SET_ROLE', res[2].role)
// store.commit('user/SET_USERICON', res[2].icon)
// if (res.organization) {
// store.commit('user/SET_ORGANIZATION', res[2].organization)
// }
// next()
// })
// .catch(error => {
// console.log(error)
// store.dispatch('user/logOut').then(() => {
// next({ path: '/' })
// })
// })
}
} else {
if (whiteList.indexOf(to.path) !== -1) {
next()
} else {
next('/login')
}
}
})
在main.js中添加
import '@/permission'