require.context函數接受三個參數
directory {String} -讀取文件的路徑
useSubdirectories {Boolean} -是否遍歷文件的子目錄
regExp {RegExp} -匹配文件的正則
語法:
require.context(directory, useSubdirectories = false, regExp = /^.//)
/*
* @Description: 獲取文件名自動配置路由
* @Author: Benny
* @Date: 2019-08-02 16:20:18
* @LastEditTime: 2019-09-26 14:41:48
*/
import Vue from 'vue';
import Router from 'vue-router';
let routesConfig = [] //路由配置
const files = require.context('./views', true, /\.vue$/)
files.keys().forEach(key => {
let path = key.replace(/(\.\/|\/index|\.vue)/g, ''), //將./ /index .vue 置換為空白
fileUrl = key.replace(/\.\//g, './views/'),//匹配路徑
len = path.split('/').length,
name = files(key).default.name || path.split('/')[len - 1] //獲取文件夾名
if (fileUrl.indexOf('index.vue') != -1 && fileUrl.indexOf('signup') == -1) { //判斷是否包含 index且排除singup入口文件
routesConfig.push({
path: `/${path}`,
name: name,
meta: {
title: name
},
component: () => import(`${fileUrl}`)
})
}
})
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
...routesConfig
],
scrollBehavior(to,from,savedPosition){
return {
x:0,
y:0
}
}
})
router.beforeEach((to, from, next) => {//beforeEach是router的鉤子函數,在進入路由前執行
if (to.meta.title) {//判斷是否有標題
document.title = to.meta.title
}
next()//執行進入路由,如果不寫就不會進入目標頁
})
export default router;
還有個問題..
路由嵌套暫時解決不了= =
望有知道的大佬指點~
目前暫時是有需求的嵌套獨立成一個路由變量然后合并到routes里頭
//教師注冊轉換連路由
const signupRouter = [
{
path: '/signup',
redirect: '/signup/resume', //重定向
name: 'signup',
component: () => import('views/signup/home'),
children: [
{
path: 'resume',
meta: { title: '填寫簡歷' },
component: () => import('views/signup/resume')
},
{
path: 'train',
meta: { title: '入職培訓' },
component: () => import('views/signup/train'),
children:[
{
path: 'book',
meta: { title: '預約培訓' },
component: () => import('views/signup/train/block/_Book')
},
{
path: 'detail',
meta: { title: '待上課' },
component: () => import('views/signup/train/block/_BookDetail')
},
{
path: 'exam',
meta: { title: '測試' },
component: () => import('views/signup/train/block/_Exam')
},
{
path: 'result',
meta: { title: '測試結果' },
component: () => import('views/signup/train/block/_Result')
},
{
path: 'upload',
meta: { title: '上傳教學照片' },
component: () => import('views/signup/train/block/_Upload')
},
{
path: 'video',
meta: { title: '觀看錄像' },
component: () => import('views/signup/train/block/_Video')
}
]
}
]
},
]