vue路由異步組件案例


異步組件:頁面需要用到時候才從服務端加載的組件。

最近研究了vue性能優化,涉及到vue異步組件。一番研究得出如下的解決方案。

原理:利用webpack對代碼進行分割是異步調用組件前提。下面介紹的是怎么實現異步組件。

案例:

首先是組件,創建四個組件分別命名為first、second、three和four;內容如下

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 = [ 
 {   //當首次進入頁面時,頁面沒有顯示任何組件;讓頁面一加載進來就默認顯示first頁面 
 path:'/', //重定向,就是給它重新指定一個方向,加載一個組件; 
 component:first 
 }, 
 { 
 path:'/first', 
 component:first
 }, 
 { 
 path:'/second', 
 component:second
 }, { 
 path:'/three', 
 component:three
 }, 
 { 
 path:'/four', 
 component:four
 } 
//這里require組件路徑根據自己的配置引入 
] 
//最后創建router 對路由進行管理,它是由構造函數 new vueRouter() 創建,接受routes 參數。 
  
 const router = new VueRouter({ 
 routes 
}) 
  
export default router; 

最后,如果想要讓build之后的代碼更便於識別,配置webpack代碼

運行 npm run  build結果

注意方案1和方案2只能用一個。然后運行項目試驗一下就可以了。


免責聲明!

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



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