// main.js
import router from './router'
new Vue({
router,
...
})
// router/index.js
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const arr = [
{
path: '',
name: '',
meta: {
title: '',
icon: '',
authrity: true,
...
},
// 懒加载
component: () => import(/* webpackChunkName: "login", webpackPrefetch: true */ '@/views/login'),
}
]
export default new Router({
mode: 'history', // require service support
base: process.env.BASE_URL || '/',
scrollBehavior: () => ({ y: 0 }),
routes: arr,
})
路由守卫
const router = new VueRouter({ ... }) //这是路由配置,我就不多说了
const whiteList = ['/error', '/register/regindex', '/register/userauthent', '/register/submit'] // 路由白名单
vueRouter.beforeEach(function(to,from,next){
console.log("进入守卫");
if (userInfo.user_id>0){
console.log("登录成功");
next(); //记得当所有程序执行完毕后要进行next(),不然是无法继续进行的;
}else{
console.log("登录失败");
getUserInfo.then(res => {
if(res){
if (res.user_id){
if (res.status == 4) {
//账号冻结
next({ path: '/error', replace: true, query: { noGoBack: true } })
}
if (res.status == 3) {
//认证审核中
next({ path: '/register/submit', replace: true, query: { noGoBack: true } })
}
if (res.status != 1 && res.status != 3) {
if (!res.mobile ) {
next({ path: '/register/regindex', replace: true, query: { noGoBack: true }})
} else {
//绑定完手机号了
next({ path: '/register/userauthent', replace: true, query: { noGoBack: true } })
}
}
next(); //记得当所有程序执行完毕后要进行next(),不然是无法继续进行的;
}else{
if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入
next(); //记得当所有程序执行完毕后要进行next(),不然是无法继续进行的;
}else{
next({ path: '/register/regindex', replace: true, query: { noGoBack: true }})
}
}
}else{
}
}
}).catch(()=>{
//跳转失败页面
next({ path: '/error', replace: true, query: { noGoBack: true }})
})
}
});
export default router
如果白名单太多或项目更大时,我们需要把白名单换为vue-router路由元信息meta
router.beforeEach((to, from, next) => {
if (to.matched.some(function (item) {
return item.meta.login_require
})) {
next('/login')
} else
next()
})