Async components 让您仅在实际需要时加载组件的代码,将其分割到一个单独的 bundle(chunk)中,按需获取。这减少了用户初始下载的 JavaScript。
定义 async component
js
{ defineAsyncComponent } ;
= (
()
);
Async components 让您仅在实际需要时加载组件的代码,将其分割到一个单独的 bundle(chunk)中,按需获取。这减少了用户初始下载的 JavaScript。
{ defineAsyncComponent } ;
= (
()
);
dynamic import() 告诉打包器(Vite/webpack)将 HeavyChart.vue 分割到自己的文件中,在组件第一次使用时懒加载——而不是作为主 bundle 的一部分。
Without lazy loading: main.js = app + HeavyChart + Editor + Modal + ... (huge, slow first load)
With lazy loading: main.js = app only; HeavyChart.js loads when you open the chart
大型、很少使用的组件(富文本编辑器、图表、模态框、管理面板)不需要在初始下载中。懒加载它们改善初始加载时间和 Core Web Vitals。
const HeavyChart = defineAsyncComponent({
loader: () => import("./HeavyChart.vue"),
loadingComponent: LoadingSpinner, // shown while the chunk downloads
errorComponent: ErrorDisplay, // shown if the download fails
delay: 200, // wait 200ms before showing the spinner
timeout: 5000, // give up after 5s
});
这种高级形式让您在获取期间显示加载器,失败时显示备用方案——很重要,因为懒加载引入了(通常很短的)网络延迟。
// Vue Router — each route loads its page component on demand
const routes = [
{ path: "/dashboard", component: () => import("./Dashboard.vue") },
];
懒加载路由组件是最常见且最有影响的用途——每个页面的代码仅在用户导航到它时加载。
Async components 是 Vue 的代码分割机制——这是随着应用增长而保持初始 bundle 小的关键技术。
通过按需加载重型或路由特定的组件(带可选的加载/错误 UI),您减少了用户预先下载的 JavaScript,加快首次加载。
这是一个标准的、高效的性能优化,特别是在应用于路由时。
一个包含详细解答的 IT 面试题库——从初级到高级。
捐赠