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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM