Vue2.0教程 (十二)router路由守卫

路由守卫

一、创建permission.js (src/permission.js)路由守卫入口

二、安装进度条 NProgress

# NProgress
$  npm install --save nprogress
# or
$ yarn add nprogress

三、permission.js 文件

import router from '@/router'
import store from '@/store'
import Config from '@/settings'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import { getToken } from '@/utils/auth' // getToken from cookie
import { filterAsyncRouter } from '@/store/modules/permission'
import routerAll from '@/router/router-all'

NProgress.configure({ showSpinner: false })// NProgress Configuration

const whiteList = ['/login']// no redirect whitelist

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title + ' - ' + Config.title
  }
  NProgress.start()
  if (getToken()) {
    // 已登录且要跳转的页面是登录页
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(() => { // 拉取user_info
          // 动态路由,拉取菜单
          loadMenus(next, to)
        }).catch(() => {
          store.dispatch('LogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      // 登录时未拉取 菜单,在此处拉取
      } else if (store.getters.loadMenus) {
        // 修改成false,防止死循环
        store.dispatch('updateLoadMenus')
        loadMenus(next, to)
      } else {
        next()
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

// 向后台发送请求拉取 菜单列表
export const loadMenus = (next, to) => {
  // routerAll   目前前台写死了
  // routerAll ---- 请求到后台返回的路由

  setTimeout(() => {
    const sdata = JSON.parse(JSON.stringify(routerAll))
    const rdata = JSON.parse(JSON.stringify(routerAll))
    const sidebarRoutes = filterAsyncRouter(sdata)
    const rewriteRoutes = filterAsyncRouter(rdata, true)
    rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
    console.log(rewriteRoutes)
    store.dispatch('GenerateRoutes', rewriteRoutes).then(() => { // 存储路由
      router.addRoutes(rewriteRoutes) // 动态添加可访问路由表
      next({ ...to, replace: true })
    })
    store.dispatch('SetSidebarRouters', sidebarRoutes)
  }, 100)
}

router.afterEach(() => {
  NProgress.done() // finish progress bar
})

四、mian.js 使用

import './permission.js' // permission control

五、其他文件说明

4.1 getToken (是否登录成功的token)
4.2 Config.title ( 当前title的标题 )
4.3 routerAll (模拟后台接口返回数据)(src/router/router-all.js)
/**
 * 本地所有的路由,用于与线上的路由合并参数
 */
const routerAll = [
  {
    path: '/nested',
    component: 'Layout',
    name: 'nested',
    meta: { title: '账号管理', icon: 'user' },
    children: [
      {
        path: 'menu1',
        name: 'menu1',
        component: 'nested/menu1/menu1-1',
        meta: { title: '菜单1', icon: 'user' }
      },
      {
        path: 'menu2',
        name: 'menu2',
        component: 'nested/menu1/menu1-2',
        meta: { title: '菜单2', icon: 'user' }
      }
    ]
  },
  {
    path: '/nested2',
    component: 'Layout',
    name: 'nested2',
    meta: { title: '菜单管理', icon: 'user' },
    children: [
      {
        path: 'menu3',
        name: 'menu3',
        component: 'nested/menu2/menu1-1',
        meta: { title: '菜单12', icon: 'user' }
      },
      {
        path: 'menu4',
        name: 'menu4',
        component: 'nested/menu2/menu1-2',
        meta: { title: '菜单22', icon: 'user' }
      }
    ]
  }
]

export default routerAll
4.4 filterAsyncRouter (store/permission.js) 完整代码,需要的自己了解下
import { constantRouterMap } from '@/router'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    sidebarRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers

      state.routers = constantRouterMap.concat(
        [
          {
            name: 'dashboard',
            path: '/dashboard',
            fullPath: '/dashboard',
            meta: {
              icon: 'dashboard',
              title: '首页'
            },
            children: []
          }
        ],
        routers
      )
    },
    SET_SIDEBAR_ROUTERS: (state, routers) => {
      state.sidebarRouters = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, asyncRouter) {
      commit('SET_ROUTERS', asyncRouter)
    },
    SetSidebarRouters({ commit }, sidebarRouter) {
      commit('SET_SIDEBAR_ROUTERS', sidebarRouter)
    }
  }
}

export const filterAsyncRouter = (
  routers,
  lastRouter = false,
  type = false
) => {
  // 遍历后台传来的路由字符串,转换为组件对象
  return routers.filter((router) => {
    if (type && router.children) {
      router.children = filterChildren(router.children)
    }
    if (router.component) {
      if (router.component === 'Layout') {
        // Layout组件特殊处理
        router.component = Layout
      } else if (router.component === 'ParentView') {
        router.component = ParentView
      } else {
        const component = router.component
        router.component = loadView(component)
      }
    }
    if (router.children != null && router.children && router.children.length) {
      router.children = filterAsyncRouter(router.children, router, type)
    } else {
      delete router['children']
      delete router['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView') {
        el.children.forEach((c) => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

export const loadView = (view) => {
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default permission
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值