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) {
    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,转载请注明出处

猜你喜欢

转载自blog.csdn.net/qq_35942348/article/details/99300545