如何在VueJs中添加动态/异步/惰性组件

如何在VueJs中添加动态/异步/惰性组件

问题描述:

我想根据某些情况动态将子组件添加到父组件中. 我想出了以下伪代码

I want to add child components in parent components on the fly based on some conditions. I have come up with following pseudo-code

If currentView == 'a'
    load component A1
    load component A2
ElseIf currentView == 'b'
    load component B2
    load component B3

我知道我们可以在父组件中注册所有组件,例如:

I know we can register all components in parent component like:

Vue.component('a1-component', require('./A1Component.vue'));
Vue.component('a2-component', require('./A2Component.vue'));

但是我有很多这样的子组件,需要时只需要加载所需的组件.因此,最初加载所有组件是一项开销.

But I have a lot of such child components and I need to load only the required components when needed. So loading all components initially is an overhead.

我尝试了 动态组件 异步组件 Js.所有动态组件都被完全加载,所以它不是我想要的.我不确定如何使用异步组件来实现这一目标.

I have tried Dynamic components and async-components in Vue Js. All Dynamic components are loaded altogether so its not what I want. I am not sure how Async components can be utilized to achieve this.

我正在使用Laravel 5.4,VueJs 2.3.3和Webpack.

I am using Laravel 5.4, VueJs 2.3.3 and Webpack.

您可以结合使用异步组件和动态导入来实现此目的

you can combine async component and dynamic import to achieve this

Vue.component('foo', () => {
    if(currentView === 'a') {
      return import('./A1Component.vue')
    } else {
      return import('./B2Component.vue')
    }
})

要使用动态导入,您需要在Webpack中添加syntax-dynamic-import插件

to use dynamic import, you'll need add syntax-dynamic-import plugin to your Webpack

Babel插件: https://babeljs.io/docs/plugins/syntax-dynamic-import/

Babel plugin: https://babeljs.io/docs/plugins/syntax-dynamic-import/

Webpack插件: https://github.com/airbnb/babel-plugin-dynamic-import- webpack

Webpack Plugin: https://github.com/airbnb/babel-plugin-dynamic-import-webpack