index.js 2.11 KB
Newer Older
xulili's avatar
xulili committed
1 2 3
import Vue from 'vue'
import VueRouter from 'vue-router'

Z's avatar
Z committed
4 5 6 7 8 9 10 11 12
// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import store from '@/store/index'
import util from '@/libs/util.js'

// 路由数据
import routes from './routes'
xulili's avatar
xulili committed
13

Z's avatar
Z committed
14 15 16 17 18 19 20 21 22 23 24
// fix vue-router NavigationDuplicated
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return VueRouterPush.call(this, location).catch(err => err)
}
const VueRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (location) {
  return VueRouterReplace.call(this, location).catch(err => err)
}

Vue.use(VueRouter)
xulili's avatar
xulili committed
25

Z's avatar
Z committed
26
// 导出路由 在 main.js 里使用
xulili's avatar
xulili committed
27 28 29 30
const router = new VueRouter({
  routes
})

Z's avatar
Z committed
31 32 33 34
/**
 * 路由拦截
 * 权限验证
 */
xd's avatar
xd committed
35
router.beforeEach(async (to, from, next) => {
Z's avatar
Z committed
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  // 确认已经加载多标签页数据 https://github.com/d2-projects/d2-admin/issues/201
  await store.dispatch('d2admin/page/isLoaded')
  // 确认已经加载组件尺寸设置 https://github.com/d2-projects/d2-admin/issues/198
  await store.dispatch('d2admin/size/isLoaded')
  // 进度条
  NProgress.start()
  // 关闭搜索面板
  store.commit('d2admin/search/set', false)
  // 验证当前路由所有的匹配中是否需要有登录验证的
  if (to.matched.some(r => r.meta.auth)) {
    // 这里暂时将cookie里是否存有token作为验证是否登录的条件
    // 请根据自身业务需要修改
    const token = util.cookies.get('token')
    if (token && token !== 'undefined') {
      next()
    } else {
      // 没有登录的时候跳转到登录界面
      // 携带上登陆成功之后需要跳转的页面完整路径
      next({
        name: 'login',
        query: {
          redirect: to.fullPath
        }
      })
      // https://github.com/d2-projects/d2-admin/issues/138
      NProgress.done()
    }
  } else {
    // 不需要身份校验 直接通过
    next()
  }
xd's avatar
xd committed
67
})  
Z's avatar
Z committed
68 69 70 71 72 73 74 75 76 77

router.afterEach(to => {
  // 进度条
  NProgress.done()
  // 多页控制 打开新的页面
  store.dispatch('d2admin/page/open', to)
  // 更改标题
  util.title(to.meta.title)
})

xulili's avatar
xulili committed
78
export default router