vue中路由按需加載的幾種方式


使用vue-cli構建項目后,我們會在Router文件夾下面的index.js里面引入相關的路由組件,如:

import Hello from '@/components/Hello'
import Boy from '@/components/Boy'
import Girl from '@/components/Girl'

普通加載的缺點:

webpack在打包的時候會把整個路由打包成一個js文件,如果頁面一多,會導致這個文件非常大,加載緩慢

1、require.ensure()實現按需加載

  • 語法:
require.ensuire(dependencies:String[],callback:function(require),errorCallback:function(error),chunkName:String)
  • vue中使用:
const List = resolve =>{ require.ensure([],()=>{ resolve(require('./list')) },'list') }

2、vue異步組件技術

在router中配置,使用這種方法可以實現按需加載,一個組件生成一個js文件

  • vue中使用:
{
path: '/home',
name: 'home',
component:resove => require(['@/components/home'],resolve)
}

3、使用動態的import()語法(推薦使用這種)

  • vue中使用:
//沒有指定webpackChunkName,每個組件打包成一個js文件
const test1 = ()=>import('@/components/test1.vue') 
const test2 = ()=>import('@/components/test2.vue')

//指定了相同的webpackChunkName,會合並打包成y一個js文件
const test3 = ()=>import(/* webpackChunkName:'grounpTest' */ '@/components/test3.vue') 
const test4 = ()=>import(/* webpackChunkName:'grounpTest' */ '@/components/test4.vue')

const router = new VueRouter({
    routes: [
        { path: '/test1', component: test1 },
        { path: '/test2', component: test2 },
        { path: '/test3', component: test3 },
        { path: '/test4', component: test4 }
    ]
 })

注:

  • /* webpackChunkName: 'grounpTest' */使用命名chunk,一個特殊的注釋語法來提供 chunk name (需要 Webpack > 2.4)


免責聲明!

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



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