在使用vue.js做管理後臺的時候,路由不是寫死在前端的,而是用戶登錄後,通過接口動態去後臺獲取的,這裏就產生了如果將動態獲取的路由加載進來的問題。
我使用的是UI框架是ElementUI,參考了花褲衩封裝的後臺管理框架,所以我不會貼上所有代碼,僅僅是部分吧,這裏的難度是這樣:接口獲取的數據中,component是一段字符串,例如下面代碼所示:
{
path: '/page',
name: 'Page',
component: 'Layout',
redirect: 'noredirect',
meta: {
title: '頁面模板',
icon: 'guide'
},
children: [{
path: 'dashboard',
name: 'PageDashboard',
meta: {
title: '儀表盤頁'
},
component: 'template/dashboard/index'
}
}
]
}
前端要將’template/dashboard/index’頁面動態加載出來,所以我們定義一個js:import_component.js
module.exports = file => () => import('@/views/' + file + '.vue')
在使用的地方(更加框架,是在permission.js使用)引入:
const importRouter = require('@/router/import_router')
function filterAsyncRouter(asyncRouterMap) {
const accessedRouters = asyncRouterMap.filter(route => {
if (route.component) {
if (route.component === 'Layout') {
route.component = Layout
} else {
route.component = importRouter(route.component)
}
}
if (route.children && route.children.length) {
route.children = filterAsyncRouter(route.children)
}
return true
})
return accessedRouters
}
這裏不再多做解釋了,如果各位在工作中遇到了要vue.js前端獲取動態路由的情況,一定會遇到這個問題,而這個問題在網上確沒人解答,所以我把一些重點代碼放上這裏來了。