loading...

1-line solution for importing and registering your Vue component

anzelika profile image Anzelika ใƒป1 min read

Today I was working on some Vuetify themes and was pleasantly surprised to learn an elegant 1-line solution to import and register a component. The pattern I usually saw in Vue projects was this:

<template>
  <v-app>
    <home-system-bar />
    <home-view />
    <home-footer />
  </v-app>
</template>
<script>
import SystemBar from '@/layouts/home/SystemBar'
import View from '@/layouts/home/View'
import Footer from '@/layouts/home/Footer'
  export default {
    components: {
      HomeSystemBar: SystemBar,
      HomeView: View,
      HomeFooter: Footer
  }
}
</script>

Above you can see that the components are imported separately and then registered in the components object. There is actually no need for a separate line to import, you may do all of it in components with an arrow function expression:

<template>
  <v-app>
    <home-system-bar />
    <home-view />
    <home-footer />
  </v-app>
</template>

<script>
  export default {
    name: 'HomeLayout',
    components: {
      HomeSystemBar: () => import('@/layouts/home/SystemBar'),
      HomeView: () => import('@/layouts/home/View'),
      HomeFooter: () => import('@/layouts/home/Footer')
    },
  }
</script>

How cool is that? When dealing with multiple imported components, this certainly makes things cleaner ๐Ÿงน

Posted on by:

anzelika profile

Anzelika

@anzelika

Self-taught front end pixie. Coffee enthusiast. Cat obsessionist. Vuetify contributor.

Discussion

pic
Editor guide
 

It's not a good idea to use this all the time. Importing components this way tells webpack to split the components into separate chunks. In your example this will result in 3 separate requests for the components being used instead of them being bundled together which will slow down the page load.

This approach is good if you are using components that are not initially rendered (and may not end up being needed) as it will reduce the initial bundle size. For example if you have a modal component that only becomes visible (using v-if) if the user clicks a button and there is a reasonable chance they won't click the button at all. In that case it might be better to import the component this way (dynamic import) and not have that component included in the initial bundle.

 

Thanks I'll have to try this