How to add dynamic/async/lazy components in VueJs

*爱你&永不变心* 提交于 2020-01-06 05:23:18

问题


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.

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.

I am using Laravel 5.4, VueJs 2.3.3 and Webpack.


回答1:


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')
    }
})

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

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

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




回答2:


Install required babel plugin:

npm install --save-dev babel-plugin-syntax-dynamic-import

Create .babelrc in your project root, include bellow short code in file:

{
    "plugins": ["syntax-dynamic-import"]
}

after you can import with this way :

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

finaly run npm build(vue-cli) or npm run watch(laravel)




回答3:


Hey man I was on this same kind of problem googled almost 4-5 hours.

The splitting didn't work as I expected. With babel preset es2015 it did work just fine on the DEV server, when building the code uglifier errored. After I got it to build, it worked beautifully. I don't think you have to tell webpack to split the code, it's all automagical when you jsut use the right type of importing, and that is the const Foo = () => import('./Foo.vue') type

All the imports done like that create a split point, and if you don't want it to split, yo uhave to take that extra step in the docs Yes, but it's not per folder, but per FILE basis so if you have 5 folders with 25 files, it'll become 25 bundle files, automatically loaded when needed

This would definitely help - https://vuejsdevelopers.com/2017/07/03/vue-js-code-splitting-webpack/



来源:https://stackoverflow.com/questions/45993715/how-to-add-dynamic-async-lazy-components-in-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!