React实现路由懒加载: React官方提供了React.lazy()函数来实现路由的懒加载。使用React.lazy()函数需要配合React的Suspense组件来使用。
const Home = React.lazy(() => import('./Home'));
const About = React.lazy(() => import('./About'));
这样,在需要使用这些组件的地方,可以像使用普通组件一样使用它们。
import React, { Suspense } from 'react';
function App() {
return (
Loading... }>
{/* 路由配置 */}
在Suspense组件中,可以设置fallback属性来指定在组件加载完成前显示的loading状态。
Vue实现路由懒加载: Vue官方提供了Vue异步组件特性来实现路由的懒加载。使用Vue异步组件特性需要使用Vue的工厂函数(Vue.extend())来动态创建组件。
const Home = () => import('./Home');
const About = () => import('./About');
这样,在需要使用这些组件的地方,可以像使用普通组件一样使用它们。
const routes = [
{ path: '/home', component: Home },
{ path: '/about', component: About },
]
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const router = new VueRouter({
routes
});
new Vue({
router,
render: h => h(App)
}).$mount('#app');
这样,路由组件将会在访问对应路由时进行懒加载。