vue自动路由-单页面项目(非build时构建)

这是一个什么项目?

答:这是一个单页面的vue.js项目,主要为了实现在非build时,进行自动路由。简单点说,就是在请求页面时,根据url进行动态添加路由。

自动路由有什么限制吗?

答:有,因为是通过url进行动态添加,所以,在指定文件夹下,组件文件的相对路径必须与url有一定的关系。当前demo项目,url路径与modules文件夹下的组件相对路径一致。例如:

url地址:localhost:5000/home/index

组件路径:modules/home/index/index.vue

此方式的自动路由能做些什么?

答:

1.动态权限控制:在匹配不上路由时,请求后台获取是否有权限,根据后台的反馈处理是否添加路由(是否允许访问)。

2.自动跳转首页、404页面等页面

项目demo地址

vue.js单项目自动路由:https://github.com/bobowire/wireboy.samples/tree/master/vue.js/onepage

具体步骤

1.组件生成

在router文件夹下添加import.js文件,代码如下图:

 源码:

module.exports = file => () => import('@/modules/' + file + '.vue')

2.拦截路由

 在src目录下,添加autoroute.js文件,代码如下图:

源码:

import router from './router'
const _import = require('./router/import')// 获取组件的方法
router.beforeEach(async (to, from, next) => {
 // 默认的首页页面
 if (to.fullPath === '/') {
 next('/home/index')
 } else if (to.matched.length === 0) {
 // 获取组件路径
 let componentpath = to.fullPath.substring(1) + '/' + to.fullPath.substring(to.fullPath.lastIndexOf('/') + 1)
 // 添加路由
 router.addRoutes([{
 path: to.fullPath,
 name: to.fullPath.substring(to.fullPath.lastIndexOf('/') + 1),
 component: _import(componentpath)
 }])
 // 路由重匹配
 next({ ...to, replace: true })
 } else {
 next()
 }
}) 

总结

以上所述是小编给大家介绍的vue自动路由-单页面项目(非build时构建),希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!