如何在VueJs中添加动态/异步/惰性组件 [英] How to add dynamic/async/lazy components in VueJs

查看:209
本文介绍了如何在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

这篇关于如何在VueJs中添加动态/异步/惰性组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆