您正在寻找的是lazy loaded components
. 在 Vue 中,它们可以在多个点上使用。
- 在vue-router - 您可以为每个路由导入组件,仅在需要时加载:
这是如何定义一个将由 webpack 自动进行代码拆分的异步组件:
const Foo = () => import('./Foo.vue')
您还可以将组件分组到同一个块中:
const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue')
const Bar = () => import(/* webpackChunkName: "group-foo" */ './Bar.vue')
const Baz = () => import(/* webpackChunkName: "group-foo" */ './Baz.vue')
- 第二个选项是Dynamic/Async components,可以在 .vue 文件中使用,如下所示:
Vue.component(
'async-webpack-example',
// The `import` function returns a Promise.
() => import('./my-async-component')
)
它甚至支持直接从包装盒中加载状态:
const AsyncComponent = () => ({
// The component to load (should be a Promise)
component: import('./MyComponent.vue'),
// A component to use while the async component is loading
loading: LoadingComponent,
// A component to use if the load fails
error: ErrorComponent,
// Delay before showing the loading component. Default: 200ms.
delay: 200,
// The error component will be displayed if a timeout is
// provided and exceeded. Default: Infinity.
timeout: 3000
})