Arvind Bhardwaj
Arvind Bhardwaj

Reputation: 5301

How to add dynamic/async/lazy components in 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.

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.

Upvotes: 0

Views: 4893

Answers (3)

Isaac ghorbani
Isaac ghorbani

Reputation: 71

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)

Upvotes: 2

Meet Zaveri
Meet Zaveri

Reputation: 3059

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/

Upvotes: 0

cwang
cwang

Reputation: 1104

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

Upvotes: 3

Related Questions