import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export const constantRoutes = [
{
path: '/',
redirect: '/home',
children: [{
path: 'home',
name: 'Home',
component: () => import('@/views/Home/index'),
meta: { title: '/home', icon: 'home' }
}]
},
{
path: '/NotFound',
component: () => import('@/views/NotFound'),
hidden: true
},
{ path: '*', redirect: '/NotFound', hidden: true }
]
// 路由自动化注册
function getAutoRegisteredRoutes() {
// require.context(目录,是否检索子文件,文件名正则表达式)
const requireComponent = require.context('@/views', true, /.vue$/) // 找到views路径下的所有vue文件
// keys返回所有匹配到的文件数组(包含路径) 返回类似“./NotFound.vue”和“./components/Button.vue”
const allViewFilesPath = requireComponent.keys()
// 过滤掉路径中包含 /_ 的文件路径,一般以“_”开头的文件夹或文件都是局部组件
const filterFiles = allViewFilesPath.filter(path => {
return !/\/_/.test(path)
})
const routesChildren = filterFiles.map(fileName => {
// require.context 返回的是一个函数,requireComponent也就相当于一个函数
// 返回的对象实际上是一个模块对象 有default属性
const componentConfig = requireComponent(fileName)
var componentName = fileName.replace(/^\.\//, '').replace(/\.vue$/, '')// 剥去文件名开头的 `./` 和`.vue`结尾的扩展名
var componentNameRe = componentName.replace(/\//g, '-') // 设置name为文件夹名-indexcreateRouter1
// 根据路径注册成组件 componentConfig.default会返回Vue会返回Vue 组件本身。
const component = Vue.component(componentNameRe, componentConfig.default || componentConfig)
// 除去constant路由的重新注册
if (componentName.indexOf('home/index') !== -1 || componentName.indexOf('login/index') !== -1 || componentName.indexOf('404') !== -1) {
componentName = ''
componentNameRe = ''
return
}
const result = {
path: componentName,
name: componentNameRe,
component,
meta: { title: componentName }
}
return result
})
return routesChildren
}
function getRoutes() {
return [
// 如果是管理系统,需要引用组件就写在children里面
// {
// path: '/',
// component: Layout,
// children: getAutoRegisteredRoutes()
// },
getAutoRegisteredRoutes(),
...constantRoutes
]
}
function createRouter() {
return new Router({
scrollBehavior: () => ({ y: 0 }),
routes: getRoutes()
})
}
const router = createRouter()
export function resetRouter() {
const newRouter = createRouter()
router.matcher = newRouter.matcher // reset router
}
export default router