我們?cè)谟胿ue.js寫(xiě)單頁(yè)面應(yīng)用時(shí)试浙,會(huì)出現(xiàn)打包后的JavaScript包非常大,影響頁(yè)面加載卷仑。
我們都知道圖片的懶加載峻村。當(dāng)圖片不出現(xiàn)在視口時(shí),我們不加載這張圖片锡凝。那么我們是不是可以實(shí)現(xiàn)粘昨,路由的懶加載。當(dāng)我們用到某個(gè)路由后,才去加載對(duì)應(yīng)的組件张肾,這樣就會(huì)更加高效芭析。
實(shí)現(xiàn)這樣的功能,我們需要<strong>結(jié)合Vue的異步組件和webpack的code splitting feature吞瞪。</strong>
下面開(kāi)始研究路由的懶加載如何實(shí)現(xiàn)馁启,以及它的效果。
首先芍秆,我們創(chuàng)建一個(gè)webpack模板的項(xiàng)目
vue init webpack my-project
cd my-project
npm install
我們添加路由惯疙,看下默認(rèn)情況下,單頁(yè)應(yīng)用如何加載js妖啥。
我們先在src/components/創(chuàng)建一個(gè)文件New.vue
<template>
<div>
<h1>vue-router懶加載</h1>
<h2>new doc</h2>
</div>
</template>
<script>
export default { }
</script>
<style>
h1 {
color: red;
}
</style>
在App.vue 文件添加兩個(gè)鏈接
<template>
<div id="app">
![](./assets/logo.png)
<router-link to="/">Go to hello</router-link>
<router-link to="/new">Go to new</router-link>
<router-view></router-view>
</div>
</template>
在src/router/index.js 文件中添加路由
import Vue from 'vue'
import Router from 'vue-router'
import Hello from 'components/Hello'
import New from 'components/New'
Vue.use(Router)
export default new Router({
routes: [{
path: '/',
name: 'Hello',
component: Hello
}, {
path: '/new',
name: 'New',
component: New
}]
})
現(xiàn)在我們打包文件
npm run build
打包完后霉颠,打開(kāi)頁(yè)面(如何不能打開(kāi),請(qǐng)自行解決荆虱。我配置了nginx蒿偎,所以可以直接打開(kāi))
http://localhost/mall/dist/index.htm#/
我們看下,打開(kāi)網(wǎng)頁(yè)后怀读,加載了哪些資源诉位。
現(xiàn)在,我們切換路由
http://localhost/mall/dist/index.htm#/new
我們發(fā)現(xiàn)菜枷,沒(méi)有新的資源加載不从。
因?yàn)橐淮涡约虞d了所有js。如果你的應(yīng)用很大犁跪,那么這個(gè)時(shí)候應(yīng)用打開(kāi)會(huì)很慢。
用路由懶加載歹袁,看看效果如何
修改src/router/index.js 文件
import Vue from 'vue'
import Router from 'vue-router'
// import Hello from 'components/Hello'
// import New from 'components/New'
Vue.use(Router)
// 把路由對(duì)應(yīng)的組件定義成異步組件
const Hello = resolve => {
require.ensure(['components/Hello.vue'], () => {
resolve(require('components/Hello.vue'))
})
}
const New = resolve => {
require.ensure(['components/New.vue'], () => {
resolve(require('components/New.vue'))
})
}
export default new Router({
routes: [{
path: '/',
name: 'Hello',
component: Hello
}, {
path: '/new',
name: 'New',
component: New
}]
})
打包成功后坷衍,再打開(kāi)頁(yè)面
http://localhost/mall/dist/index.htm#/
看下此時(shí)加載的資源
對(duì)比上一次,我發(fā)現(xiàn)此時(shí)加載的資源多了一個(gè)js文件条舔。而這個(gè)js文件的內(nèi)容包含了Hello.vue文件的所有內(nèi)容枫耳。
下面我們切換路由
http://localhost/mall/dist/index.htm#/new
發(fā)現(xiàn)新加載了一個(gè)js文件。打開(kāi)這個(gè)js,發(fā)現(xiàn)其中包含了孟抗,New.vue文件的所有內(nèi)容迁杨。
現(xiàn)在,我們實(shí)現(xiàn)了按需加載組件凄硼,而不是一次性將所有js加載完铅协。不必?fù)?dān)心一次性加載完,導(dǎo)致頁(yè)面遲遲打不開(kāi)的情況摊沉。
修改New.vue文件
<script>
//增加了axios模塊的引用
import axios from 'axios'
console.log(typeof axios, 11)
export default {
name: 'hello',
data() {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
</script>
打包后狐史,打開(kāi)文件
http://localhost/mall/dist/index.htm#/new
你會(huì)發(fā)現(xiàn)用來(lái)異步加載New組件的js增大了很多,這是因?yàn)槠渲邪薬xios的代碼。
好了骏全,路由懶加載的實(shí)現(xiàn)就這么簡(jiǎn)單苍柏。更多內(nèi)容請(qǐng)看官方文檔