vue 路由懶加載 總路由配置動態引入

一般的方式

import shopRoutes from ‘./shop/index.routes.js’;
import storeRoutes from ‘./store/index.routes.js’;
import priceRoutes from ‘./price/index.routes.js’;

const routes = {
{ path: ‘/’, component: Index, children: [
{ path: ‘’, component: Loading },
shopRoutes ,
storeRoutes ,
priceRoutes,
] },
{ path: ‘*’, component: Index },
}
這種方式,還是優化過的,沒有在同一個文件裏引入所有的,至少進行了功能分區。但是還是複雜的,每加一個需要自己再添加一次。

那就幹掉這種low比的方式 做一個總路由配置動態引入

const routesList = [];
function importAll® {
r.keys().forEach((key) => routesList .push(r(key).default));
}
// 這裏會解析目錄下 xx.routes.js 文件,如果需要添加新的路由,請按此方案命名
importAll(require.context(’.’, true, /.routes.js/));
const routes = [
{ path: ‘/’, component: Index, children: [
{ path: ‘’, component: Loading },
…routesList ,
] },
{ path: ‘*’, component: Index },
];
//這樣就可以做到動態引入,不需要手動添加 就是如此酸爽 注意命名規則要一致
// 還沒理解透的同學可以去看看webpack官網 鏈接奉上https://webpack.js.org/configuration/entry-context/#context

路由懶加載

export default{
path:’/index’,
name:‘Index’,
//這一行是最重要的
component:()=> import(/webpackChunkName:“index”/’…/views/index/index.vue’),
//把相同的模塊打入一個chunk(塊)
children:[ ],
meta:{
//自定義字段
requireAuth:true
}
}

原理

當用戶訪問到Index頁面的時候,纔去引入加載這個模塊

優點

因爲vue大部分是做單頁應用,首屏加載會比較慢,這種方式可以大幅度縮短加載時間,優化用戶體驗

覺得學到了的小夥伴可以在評論區扣個666,轉載請註明出處

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章