/**
* 根据 pages 目录自动添加路由
* 参考 nuxt https://zh.nuxtjs.org/guide/routing
*/
import Vue from 'vue'
import Router, { Route } from 'vue-router'
import { interopDefault } from './util'
import OfflineRedirect from './hooks/offline'
import disposer from '@/utils/disposer'
Vue.use(Router)
interface RouteType {
path:string,
[key:string]:any
}
const context = require.context('../pages', true, /\.vue$/, 'lazy')
/**
* 根据页面的路径 设置路由的path
* @param page /Home/Index => path: /home
* /Home/Once => path: /home/once
* @param prefix
*/
function getPath(pages:string[], prefix = '/') {
const [first, second = ''] = pages
const firstPath = first.toLocaleLowerCase()
const secondPath = second.toLocaleLowerCase()
if (firstPath === 'index') {
return prefix
}
if (secondPath.startsWith('_')) {
return `${prefix}${firstPath}:${secondPath.slice(1)}`
}
if (secondPath === 'index' || secondPath === '') {
return `${prefix}${firstPath}`
}
return `${prefix}${firstPath}/${secondPath}`
}
/**
* 给路由设置 component 属性
* 懒加载组件
* @param route
* @param path
*/
function importComponent(route:RouteType, pathKeys:string[]) {
const path = pathKeys.join('/')
route.component = () => interopDefault(import(`@/pages/${path}.vue`))
}
/**
* 设置子路由
* @param r
*/
function getChildrens(route:RouteType, pathKeys:string[]) {
const [, pageName] = pathKeys
const path = pageName.toLocaleLowerCase()
if (!route.children) {
route.children = []
}
const childRoute:RouteType = {
path: ''
}
importComponent(childRoute, pathKeys)
if (path !== 'index') {
childRoute.path = path
childRoute.name = pathKeys.join('')
} else {
childRoute.name = route.name
delete route.name
}
route.children.push(childRoute)
}
const paths = context
.keys()
.map(v => v.replace(/\.(\/|vue)/g, '').split('/'))
const reverseKeys = paths.sort((a, b) => a.length - b.length)
// const pathProxies:Record<string, RouteType> = {}
const onePages = reverseKeys.filter(v => v.length === 1)
.reduce((current, next) => current.concat(next), [])
const pathProxies:Record<string, RouteType> = {}
reverseKeys.forEach((pathKeys) => {
const key = getPath(pathKeys)
const [firstPath] = pathKeys
if (onePages.indexOf(firstPath) > -1 && pathKeys.length === 2) {
const route = pathProxies[getPath([firstPath])]
getChildrens(route, pathKeys)
} else {
pathProxies[key] = {
path: key,
name: pathKeys.join('')
}
importComponent(pathProxies[key], pathKeys)
}
})
const routes = Object.values(pathProxies)
const base = `${process.env.PREFIX}/`
const router = new Router({
base,
mode: 'history',
scrollBehavior(to:Route, from:Route) {
return { x: 0, y: 0 }
},
routes
})
router.beforeEach(OfflineRedirect)
router.afterEach(() => {
disposer.dispose()
})
router.onError((error) => {
const pattern = /Loading chunk chunk-(\w)+ failed/g
const isChunkLoadFailed = pattern.test(error.message)
const targetPath = (router as any).history.pending.fullPath
if (isChunkLoadFailed) {
router.replace(targetPath)
}
})
export default router
vue-router封装
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- (1) export 和 export default 的区别 export ( import ) 可以有多个,e...
- 介绍: vue-cli、axios、vue-router、vuex,安装流程不再赘述,文件目录如下: 一、axio...
- 本项目选择vuecli3+vant进行移动端页面开发。本文是针对导航栏进行的简单封装 1、在main.js中导入N...
- 不知道说什么开头了,还是不说开头了。直接步入主题吧。 首先判断是否有tag,如果没有则默认隐藏 我的思路是监听ro...
- 实际经历,在公司vue项目中,一个商品页面可以从两个入口进入,分别是首页的一个<router-link to="/...