gpt4 book ai didi

vue.js - 防止特定的 .vue 组件被捆绑

转载 作者:行者123 更新时间:2023-12-05 07:10:59 24 4
gpt4 key购买 nike

问题:在我的 vue-cli 4 应用程序中,我想要生成生产包的 build: 脚本,其中在某些情况下不包含特定的 .vue-components。在其他情况下,它们应该包括在内。此外,这些组件存储在应用程序本身中,而不是外部库中。

我试过:动态导入 .vue-components - 假设我有一个数组:

const customPreset = ['WidgetFirst', 'WidgetSecond', ...]

和空对象:

const widgets = {}

所以我试着做了这样的事情:

customPreset.forEach(v => { Object.assign(widgets, { [v]: () => import('./' + v + '.vue') }) })
export default widgets

customPreset 更改为其他数组将允许导入另一组组件...

但这不起作用,因为 import() 不能对表达式进行操作。

那么,在各种情况下,如何将各种 .vue-components 包含到生产包中呢?也许可以通过调整 vue.config.js 来实现?

最佳答案

您正在寻找的是惰性加载组件。在 Vue 中,它们在多个点可用。

  1. vue-router - 您可以按路线导入组件,仅在需要时加载:

This is how to define an async component that will be automatically code-split by webpack:

const Foo = () => import('./Foo.vue')

您还可以将组件分组在同一 block 中:

const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue')
const Bar = () => import(/* webpackChunkName: "group-foo" */ './Bar.vue')
const Baz = () => import(/* webpackChunkName: "group-foo" */ './Baz.vue')
  1. 第二个选项是 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
})

关于vue.js - 防止特定的 .vue 组件被捆绑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60983073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com