brg
brg

Reputation: 133

Vuejs large application lazy loading dynamic components

I'm trying to build a vuejs application which will have hundreds if not thousands of "form" or "page" components that all get swapped out inside a dynamic <component is=''> tag. The problem is having to import each component. Is there a way to dynamically import components based on a route parameter? So far I have the following but it doesn't work:

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const Hello = resolve => require(['@/components/Hello.vue'], resolve)

export default new Router({
  routes: [{
    path: '/',
    name: 'Hello',
    component: Hello
  }, {
    path: '/:name',
    name: 'Dynamic',
    component : {
      template: '<component :is="$route.params.name"></component>',
      watch: {
        '$route': function(to) {
          window[to.params.name] = resolve => require(['@/components/' + to.params.name + '.vue'], resolve)
          Vue.component(to.params.name, window[to.params.name])
          console.log(to.params.name)
        }
      }
    }
  }]
})

Upvotes: 1

Views: 2087

Answers (1)

Zia
Zia

Reputation: 2710

One way to do it, assuming all components are stored in a single directory (technically they can be stored anywhere as long as the loader file grabs and imports them).

import Vue from 'vue'
import Router from 'vue-router'
import Components from './components'

Vue.use(Router)

const Hello = resolve => require(['@/components/Hello.vue'], resolve)

export default new Router({
  routes: [{
    path: '/',
    name: 'Hello',
    component: Hello
  }, {
    path: '/:name',
    name: 'Dynamic',
    component : {
      template: '<component :is="Components[$route.params.name]"></component>'
    }
  }]
})

Then inside ./components/index.js the following assuming all your components are .vue files:

const files = require.context('.', false, /\.vue$/)
const modules = {}
files.keys().forEach((key) => {
  modules[key.replace(/(\.\/|\.vue)/g, '')] = files(key)
})

export default modules

I haven't tested this implementation, but the approach to loading the directory files is how I use it in some areas where I have a dynamic number of components located in a folder that can change over time (say as more modules get installed into the application and you don't want to have to update the supportive frontend code every time).

Upvotes: 1

Related Questions