zoukankan      html  css  js  c++  java
  • vue项目实战:路由文件的配置

    /*
     * @Description: 路由入口配置文件 index.js文件
     * @Version: 2.0
     * @Autor: lhl
     * @Date: 2020-06-10 15:53:32
     * @LastEditors: lhl
     * @LastEditTime: 2020-08-20 17:05:28
     */
    import Vue from 'vue'
    import Router from 'vue-router'
    import vuecodeRouterModule from './vuecodeRouter'
    import elementRouterModule from './elementStudyRouter'
    // import HelloWorld from '@/components/HelloWorld' // 基础写法,没有懒加载,打包分离代码
    
    // 导入进度条
    import NProgress from 'nprogress'
    import 'nprogress/nprogress.css'
    
    // 简单配置 详细看  https://github.com/rstacruz/nprogress
    NProgress.inc(0.1)
    NProgress.configure({ easing: 'ease', speed: 600, showSpinner: false })
    
    Vue.use(Router)
    
    // 1、vue异步组件 --> 第一种: 异步组件将每一个组件生成一个js文件
    // 2、es6中import懒加载 ---> 第二种: 会将webpackChunkName名字相同的生成一个js文件    
    // 3、webpack提供的require.ensure() r就是resolve的意思 ---> 第三种:和第二种方法类似但是可以单独引入依赖会将名字相同的生成一个js文件    
    
    // 解决菜单多次点击报错的问题 fix vue-router NavigationDuplicated
    const VueRouterPush = Router.prototype.push
    Router.prototype.push = function push (location) {
      return VueRouterPush.call(this, location).catch(err => err)
    }
    const VueRouterReplace = Router.prototype.replace
    Router.prototype.replace = function replace (location) {
      return VueRouterReplace.call(this, location).catch(err => err)
    }
    
    const router = new Router({
      routes: [{
          path: '/',
          redirect: '/dashboard'
        },
        {
          path: '/login',
          name: 'login',
          component: () => import('@/page/login/login')
        },
        {
          path: '/',
          name: 'home',
          component: () => import('@/components/layout/home'),
          children: [{
              path: '/dashboard',
              name: 'dashboard',
              component: () => import('@/page/dashboard/index.vue'), // 第一种方式:ES6的import()方法---按需加载(常用)
              // component: resolve => require(['@/page/dashboard/index.vue'], resolve), // 第二种方式:vue的异步组件,require()方法。(按需加载)
              // component: r => require.ensure([], () => r(require('@/page/dashboard/index.vue')), 'dashboard'), // 第三种方式:webpack提供的require.ensure()  r就是resolve的意思
              // component: () => import(/* webpackChunkName: "dashboard" */ '@/page/dashboard/index.vue'), // 最优官方,懒加载和打包分离代码。(项目推荐使用)一个特殊的注释语法来提供 chunk name (需要 Webpack > 2.4)
              meta: {
                title: '首页'
              }
            },
            {
              path: '/baiduMapTest',
              name: 'baiduMapTest',
              component: () => import('@/page/baiduMap/baiduMapTest.vue'), 
              meta: {
                title: '百度地图'
              }
            },
            {
              path: '/vueBaiduMap',
              name: 'vueBaiduMap',
              component: () => import('@/page/baiduMap/vueBaiduMap.vue'),
              meta: {
                title: 'vue百度地图'
              }
            },
            ...vuecodeRouterModule,
            ...elementRouterModule,
            {
              path: '*',
              name: '404',
              component: () => import('@/page/404/notFound')
            }
          ]
        }
      ]
    })
    
    import store from '../store'
    
    const whiteList = ['/login'] // no redirect whitelist 白名单不需要登录
    // 路由全局前置钩子
    router.beforeEach((to, from, next) => {
      // console.log(to,'to')
      // 开启进度条
      NProgress.start();
      // url 注入  直接url进来
      // if(to.name != 'login' && to.name != 'dashboard'){
      //   localStorage.setItem('path', JSON.stringify(to.name))
      //   localStorage.setItem('query', JSON.stringify(to.query))
      // }
      /*登录界面登录成功之后,会把用户信息保存在会话
      存在时间为会话生命周期,页面关闭即失效。
      这里还可以做全局的loading 效果 在 router.afterEach 关闭 */
      
      // 网页标题
      if(to.meta.title){
        document.title = `${to.meta.title} | vue-manage`;
      }
      
      const token = store.state.user.token;
      // console.log(token,'token')
    
      if(token){
        if(to.path === '/login'){
          next({
            path: to.query.redirect || '/',
            query: {}
          })
        } else {
          next()
        }
      } else {
        if (whiteList.indexOf(to.path) !== -1) {
          // 点击退出时,会定位到这里
          next()
        } else {
          next({
            path: '/login',
            query: { redirect: to.fullPath }
          })
          NProgress.done()
        }
      }
    })
    
    // 路由全局后置钩子
    router.afterEach((to, from) => {
      // 进度条加载完毕
      NProgress.done()
    })
    
    export default router
    
    // 备注 vue2.2.0 以后新增了router.addRoutes 添加动态路由 比如 登录进去才可以看得到的路由 一些权限路由
    // router.addRoutes(routes: Array<RouteConfig>)
    // 动态添加更多的路由规则。参数必须是一个符合 routes 选项要求的数组
    // 使用:
    // this.$router.options.routes = routes; // 是因为,router.options.routes 不是响应式的
    // this.$router.addRoutes(routes);
    
    // 如果路由报错 Uncaught (in promise) Error: Redirected from "/dymicFrom" to "/login" via a navigation guard. 退出登录时候 location.reload();
    
    
    /*路由的 meta 属性里面添加 keepAlive 值为 true or false  keep-alive标签上使用 include、exclude max属性控制需要缓存的组件(对应组件写上name:'xxx')
      <keep-alive>
        <router-view v-if='$route.meta.keepAlive'></router-view>
      </keep-alive>
      <router-view v-if='!$route.meta.keepAlive'></router-view>
    */
    /*
     * @Description: element-ui用法 知识点路由
     * @Version: 2.0
     * @Autor: lhl
     * @Date: 2020-07-20 10:54:04
     * @LastEditors: lhl
     * @LastEditTime: 2020-08-07 10:16:33
     */ 
    
    const elementRouterModule = [
      {
        path: '/dymicFrom',
        name: 'dymicFrom',
        component: () => import('@/page/usualElementStudy/dymicFrom'),
        meta: {
          title: 'element-ui动态组件'
        }
      },
      {
        path: '/elementTable',
        name: 'elementTable',
        component: () => import('@/page/usualElementStudy/elementTable'),
        meta: {
          title: 'element-ui表格的常规用法'
        }
      },
      {
        path: '/tableDetail',
        name: 'tableDetail',
        component: () => import('@/page/usualElementStudy/tableDetail'),
        meta: {
          title: '详情界面'
        }
      }
    ]
    export default elementRouterModule
    /*
     * @Description: vue语法糖知识点路由
     * @Version: 2.0
     * @Autor: lhl
     * @Date: 2020-07-06 13:42:28
     * @LastEditors: lhl
     * @LastEditTime: 2020-08-13 18:01:00
     */ 
    const vuecodeRouterModule = [
      {
        path: '/parent',
        name: 'parent',
        component: () => import('@/page/vueStudy/parent'),
        meta: {
          title: 'vue组件通信'
        }
      },
      {
        path: '/funCom',
        name: 'funCom',
        component: () => import('@/page/vueStudy/funCom'),
        meta: {
          title: 'vue函数式组件'
        }
      },
      {
        path: '/vueRouterParmas',
        name: 'vueRouterParmas',
        component: () => import('@/page/vueStudy/vueRouterParmas'),
        meta: {
          title: 'vue路由传参'
        }
      },
      {
        path: '/vueRouterDefend',
        name: 'vueRouterDefend',
        component: () => import('@/page/vueStudy/vueRouterDefend'),
        meta: {
          title: 'vue守卫'
        }
      },
      {
        path: '/vueGrammar',
        name: 'vueGrammar',
        component: () => import('@/page/vueStudy/vueGrammar'),
        meta: {
          title: 'vue语法糖总结'
        }
      },
    ]
    export default vuecodeRouterModule

      以上代码本人项目实测!!!真实可靠,请勿随意转载~转载请注明出处~~~谢谢合作!

  • 相关阅读:
    【Vue】源码——编译过程
    FreeRADIUS 、DaloRADIUS 搭建记录
    docker 学习笔记
    wget 技巧
    Centos 部署Cobbler系统
    Cloudstack 安装记录
    利用Google GCM发送push通知到Android客户端
    利用ApnsPHP包向IOS推送消息
    Linux下SCP的使用
    Android Google购买PHP服务器端验证(订阅购买和一次性购买)
  • 原文地址:https://www.cnblogs.com/lhl66/p/13536177.html
Copyright © 2011-2022 走看看