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

博客中自动路由的原理?

答:简单点说,就是在请求页面时,根据url进行动态添加路由。

与其它自动路由博客的区别?

目前网上的博客,一般都是在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()
  }
})

  

posted @ 2019-04-30 11:44  吃西瓜的星星  阅读(887)  评论(0编辑  收藏  举报