An introduction to the Nuxt components module

An introduction to the Nuxt components module

Introduction

The Nuxt components module was designed to make you more productive. With the module, you can use your components without having to import or register them everywhere you're using them. Under the hood, the module automatically does 2 things for you:

  1. It scans through your components folder;
  2. Imports all files with the .vue extension and registers them.

That way, you can use your components on any page, layout, or other components without the need to import and register them. It is very similar to what happens when you create an _partials folder in your components directory.

What you would traditionally write this way

<template>
  <div>
    <MyComponent />
  </div>
</template>

<script>
import MyComponent from '~/components/MyComponent.vue'
export default {
  components: {
    MyComponent
  }
}
</script>

Becomes this when you use the Nuxt components module.

<template>
  <div>
    <MyComponent />
  </div>
</template>

Installation

To install the module, run yarn add @nuxt/components or npm install @nuxt/components. If you are running Nuxt v2.13 and above, you don't have to install it because it comes preinstalled when you create a new Nuxt project. All you need to do is set components to true in your nuxt.config.js file.

export default {
  components: true
}

Examples

If you have nested components, the way you use them in your templates can be slightly different. For example, if you have a directory structure like this

components/
  foo/
    Bar.vue

The component name will be based on its filename: <Bar />. However, this can get quite confusing if you have components in different directories with the same file name.

components/
  foo/
    Card.vue
  bar/
    Card.vue

It is therefore recommended to use the directory name in the filename for clarity.

components/
  foo/
    FooCard.vue
  bar/
    BarCard.vue
`

But in a case where you want to keep the filename as Card.vue, you can use the prefix option in your nuxt.config.js file:

components: [
    '~/components/',
    { path: '~/components/foo/', prefix: 'foo' },
    { path: '~/components/bar/', prefix: 'bar' }
]

With that, you can use the components as <FooCard /> and <BarCard /> in your templates without having to rename the components.

For dynamically imported components, all you need to do is add a Lazy prefix in your templates.

<template>
  <LazyComponent v-if="foo" />
  <button @click="loadLazyComponent">
    Load lazy component
  </button>
</template>

<script>
export default {
  data () {
    return {
      foo: null
    }
  },
  methods: {
    async loadLazyComponent () {
      this.foo = await this.$axios.$get('foo')
    }
  }
}
</script>

For more information or to learn about some more advanced configurations, check out this article by Krutie Patel or the docs.