vue+webpack 实现懒加载的三种方式

第一种:

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

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()
    }

猜你喜欢

转载自www.cnblogs.com/maqingyuan/p/9651643.html