最近研究了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只能用一個。然后運行項目試驗一下就可以了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。