解析vue路由異步組件和懶加載案例
最近研究了vue性能優(yōu)化,涉及到vue異步組件和懶加載。一番研究得出如下的解決方案。
原理:利用webpack對代碼進行分割是懶加載的前提,懶加載就是異步調(diào)用組件,需要時候才下載。
案例:
首先是組件,創(chuàng)建四個組件分別命名為first、second、three和four;內(nèi)容如下
first <template> <div>我是第一個頁面</div> </template> second <template> <div>我是第二個頁面</div> </template> three <template> <div>我是第三個頁面</div> </template> four <template> <div>我是第四個頁面</div> </template>
路由index.js代碼,異步組件方式有兩種,代碼中的方案1和方案2;注意:方案1需要添加syntax-dynamic-import插件
import Vue from 'vue'
import VueRouter from 'vue-router'
/*import First from '@/components/First'
import Second from '@/components/Second'*/
Vue.use(VueRouter)
//方案1
const first =()=>import(/* webpackChunkName: "group-foo" */ "../components/first.vue");
const second = ()=>import(/* webpackChunkName: "group-foo" */ "../components/second.vue");
const three = ()=>import(/* webpackChunkName: "group-fooo" */ "../components/three.vue");
const four = ()=>import(/* webpackChunkName: "group-fooo" */ "../components/four.vue");
//方案2
const first = r => require.ensure([], () => r(require('../components/first.vue')), 'chunkname1')
const second = r => require.ensure([], () => r(require('../components/second.vue')), 'chunkname1')
const three = r => require.ensure([], () => r(require('../components/three.vue')), 'chunkname2')
const four = r => require.ensure([], () => r(require('../components/four.vue')), 'chunkname2')
//懶加載路由
const routes = [
{ //當(dāng)首次進入頁面時,頁面沒有顯示任何組件;讓頁面一加載進來就默認(rèn)顯示first頁面
path:'/', //重定向,就是給它重新指定一個方向,加載一個組件;
component:first
},
{
path:'/first',
component:first
},
{
path:'/second',
component:second
}, {
path:'/three',
component:three
},
{
path:'/four',
component:four
}
//這里require組件路徑根據(jù)自己的配置引入
]
//最后創(chuàng)建router 對路由進行管理,它是由構(gòu)造函數(shù) new vueRouter() 創(chuàng)建,接受routes 參數(shù)。
const router = new VueRouter({
routes
})
export default router;
最后,如果想要讓build之后的代碼更便于識別,配置webpack代碼

運行 npm run build結(jié)果

注意方案1和方案2只能用一個。然后運行項目試驗一下就可以了。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue+elementUI實現(xiàn)動態(tài)面包屑
這篇文章主要為大家詳細介紹了vue+elementUI實現(xiàn)動態(tài)面包屑,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04
使用Vue調(diào)取接口,并渲染數(shù)據(jù)的示例代碼
今天小編就為大家分享一篇使用Vue調(diào)取接口,并渲染數(shù)據(jù)的示例代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10

