文档解释
router.addRoutes
函数签名:
router.addRoutes(routes: Array<RouteConfig>)
动态添加更多的路由规则。参数必须是一个符合 routes 选项要求的数组。
基本使用:
const routes = [
{
path: '/',
name: 'Home',
component: Home
}
]
const router = new VueRouter({
routes
})
export default router
上面为普通路由配置
使用router.addRoutes改造上面的配置,实现动态添加pageA,如下:
const router = new VueRouter({
{
path: '/',
name: 'Home',
component: Home
},})
let route=[
{
path: '/pageA',
name: 'pageA',
component: pageA,
}]
router.addRoutes(route);
export default router
添加之后等效于:
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/pageA',
name: 'pageA',
component: pageA,
}
]
const router = new VueRouter({
routes
})
export default router
这样的好处就可以做路由的权限验证:
设置一个路由数组,设置用户权限commonUser = ['pageA','pageB']],这样就可以访问pageA,pageB路由了
let route=[
{
path: '/pageA',
name: 'pageA',
component: pageA,
},
{
path: '/pageB',
name: 'pageB',
component: pageB,
},
{
path: '/pageC',
name: 'pageC',
component: pageC,
}
]
let commonUser=['pageA','pageB']
let commonUserRoute=route.filter(function(page){
return commonUser.includes(page.name)
})
console.log(commonUserRoute);
router.addRoutes(commonUserRoute);
//结果
// (2) [{…}, {…}]
// 0: {path: "/pageA", name: "pageA", component: pageA}
// 1: {path: "/pageB", name: "pageB", component: pageB}
// length: 2
// __proto__: Array(0)