1. // main.js
  2. import router from './router'
  3. new Vue({
  4. router,
  5. ...
  6. })
  1. // router/index.js
  2. import Vue from 'vue'
  3. import Router from 'vue-router'
  4. Vue.use(Router)
  5. const arr = [
  6. {
  7. path: '',
  8. name: '',
  9. meta: {
  10. title: '',
  11. icon: '',
  12. authrity: true,
  13. ...
  14. },
  15. // 懒加载
  16. component: () => import(/* webpackChunkName: "login", webpackPrefetch: true */ '@/views/login'),
  17. }
  18. ]
  19. export default new Router({
  20. mode: 'history', // require service support
  21. base: process.env.BASE_URL || '/',
  22. scrollBehavior: () => ({ y: 0 }),
  23. routes: arr,
  24. })

路由守卫

  1. const router = new VueRouter({ ... }) //这是路由配置,我就不多说了
  2. const whiteList = ['/error', '/register/regindex', '/register/userauthent', '/register/submit'] // 路由白名单
  3. vueRouter.beforeEach(function(to,from,next){
  4. console.log("进入守卫");
  5. if (userInfo.user_id>0){
  6. console.log("登录成功");
  7. next(); //记得当所有程序执行完毕后要进行next(),不然是无法继续进行的;
  8. }else{
  9. console.log("登录失败");
  10. getUserInfo.then(res => {
  11. if(res){
  12. if (res.user_id){
  13. if (res.status == 4) {
  14. //账号冻结
  15. next({ path: '/error', replace: true, query: { noGoBack: true } })
  16. }
  17. if (res.status == 3) {
  18. //认证审核中
  19. next({ path: '/register/submit', replace: true, query: { noGoBack: true } })
  20. }
  21. if (res.status != 1 && res.status != 3) {
  22. if (!res.mobile ) {
  23. next({ path: '/register/regindex', replace: true, query: { noGoBack: true }})
  24. } else {
  25. //绑定完手机号了
  26. next({ path: '/register/userauthent', replace: true, query: { noGoBack: true } })
  27. }
  28. }
  29. next(); //记得当所有程序执行完毕后要进行next(),不然是无法继续进行的;
  30. }else{
  31. if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入
  32. next(); //记得当所有程序执行完毕后要进行next(),不然是无法继续进行的;
  33. }else{
  34. next({ path: '/register/regindex', replace: true, query: { noGoBack: true }})
  35. }
  36. }
  37. }else{
  38. }
  39. }
  40. }).catch(()=>{
  41. //跳转失败页面
  42. next({ path: '/error', replace: true, query: { noGoBack: true }})
  43. })
  44. }
  45. });
  46. export default router

如果白名单太多或项目更大时,我们需要把白名单换为vue-router路由元信息meta

  1. router.beforeEach((to, from, next) => {
  2. if (to.matched.some(function (item) {
  3. return item.meta.login_require
  4. })) {
  5. next('/login')
  6. } else
  7. next()
  8. })