index.js 2.24 KB
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import Login from '@/views/Login'
// import { utils } from 'glsx-common'
// import { constants } from '@/common'
// import Home from '@/views/Home'
import E404 from '@/views/404'
// import Layout from '@/views/Layout'
Vue.use(VueRouter)
const Path = Object.freeze({
  LOGIN: '/login',
  E404: '/404'
})
// 路由
let constantRoutes = [
  {
    path: Path.LOGIN,
    name: 'login',
    component: Login,
    meta: { isBase: true, title: '登录' }
  },
  {
    path: Path.E404,
    name: '404',
    component: E404,
    meta: { isBase: true, title: '404' }
  },
  {
    path: '/',
    redirect: Path.LOGIN // 默认加载的路由
  },
  { path: '*', redirect: Path.E404 }
]

const createRouter = () => {
  return new VueRouter({
    mode: 'hash',
    routes: constantRoutes,
    scrollBehavior(to, from, savedPosition = { x: 0, y: 0 }) {
      return savedPosition
    }
  })
}

// 处理重复点击同一个路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
//判断路由是否存在
VueRouter.prototype.hasRoute = function (path) {
  return this.getRoutes().some(route => route.path === path)
}
VueRouter.prototype.constantRoutes = constantRoutes
/**
 * 重置注册的路由导航map
 */
VueRouter.prototype.reset = function () {
  const newRouter = createRouter()
  this.matcher = newRouter.matcher
}

const router = createRouter()

router.beforeEach(async (to, from, next) => {
  const session = store.getters.auth.session
  if (from.path !== '/' && session === null) {
    next(Path.LOGIN)
    return
  }
  store.dispatch('app/setCurrentPage', to.meta)
  if (from.name === null && to.path === Path.E404 && to.redirectedFrom && session === null) {
    // 页面刷新 动态路由会失效 初始化路由与左侧菜单栏
    await store.dispatch('init/init')
    if (router.hasRoute(to.redirectedFrom)) {
      next(to.redirectedFrom)
    } else {
      next(Path.LOGIN)
    }
  } else {
    if (session) {
      next()
    } else {
      if (to.path === Path.LOGIN) {
        next()
      } else {
        next(Path.LOGIN)
      }
    }
  }
})
export default router