DEV Community

Anzelika
Anzelika

Posted on

1-line solution for importing and registering your Vue component

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

How cool is that? When dealing with multiple imported components, this certainly makes things cleaner 🧹

Top comments (2)

Collapse
 
raheel98 profile image
Raheel Khan

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.

Collapse
 
kingnathanal profile image
William Britton

Thanks I'll have to try this