Vue-cli 3的发布,路由懒加载更简单了

合理使用代码分割 合并相同的模块 会让你的项目加载的更快

,
      {
        path: "路由路径",
        component: () =>
          import(/* webpackChunkName: "chunk名称 用于代码分割 " */ "组件路径")
      }

第一种
这里写图片描述

引入方式 就是正常的路由引入方式

const router = new Router({
    routes: [
		{
		   path: '/hyh',
		   component: hyh,
		   name: 'hyh'
		}
	]
})

第二种

const router = new Router({
    routes: [
		 {
		       path: '/index',
		       component: (resolve) => {
		           require(['../components/index/index'], resolve) // 这里是你的模块 不用import去引入了
		       }
		   }
	]
})

第三种 推荐!!!

// r就是resolve
const list = r => require.ensure([], () => r(require('../components/list/list')), 'list');
// 路由也是正常的写法  这种是官方推荐的写的 按模块划分懒加载 
const router = new Router({
    routes: [
		{
		   path: '/list/blog',
		   component: list,
		   name: 'blog'
		}
	]
})

打包后的JS按照你的模块划分去拆分

这里写图片描述

介绍一种管理路由的方式

// 定义一个路由的数组 类似于白名单黑名单
const defaultRouterArr = ['/list/share']
router.beforeEach((to, from, next) => {
// 如果匹配到这个数组 
    if (defaultRouterArr.indexOf(to.path) >= 0) {
        // 执行各种操作 比如让他去登录  不让她进去等等  通过next方法来控制  详细参考vue路由
        next()
    } else {
        next()
    }
})
Logo

前往低代码交流专区

更多推荐