Enabling Auto-Discovery

Starting from v2.13, Nuxt can auto import your components when used in your templates. To activate this feature, set components: true in your configuration:

nuxt.config.js

  1. export default {
  2. components: true
  3. }

Component Discovery - 图1

Check out how to configure component auto-discovery.

Using Components

Once you create your components in the components directory they will then be available throughout your app without the need to import them.

  1. | components/
  2. --| TheHeader.vue
  3. --| TheFooter.vue

layouts/default.vue

  1. <template>
  2. <div>
  3. <TheHeader />
  4. <Nuxt />
  5. <TheFooter />
  6. </div>
  7. </template>

Component Discovery - 图2

See live demo or video example.

Component Names

If you have components in nested directories such as:

  1. | components/
  2. --| base/
  3. ----| foo/
  4. ------| Button.vue

The component name will be based on its own path directory and filename. Therefore, the component will be:

  1. <BaseFooButton />

Component Discovery - 图3

For clarity, it is recommend that the component file name matches its name. (So, in the example above, you could rename Button.vue to be BaseFooButton.vue.)

If you want to use a custom directory structure that should not be part of the component name, you can explicitly specify these directories:

  1. | components/
  2. --| base/
  3. ----| foo/
  4. ------| Button.vue

nuxt.config.js

  1. components: {
  2. dirs: [
  3. '~/components',
  4. '~/components/base'
  5. ]
  6. }

And now in your template you can use FooButton instead of BaseFooButton.

pages/index.vue

  1. <FooButton />

Component Discovery - 图4

Consider naming your components and directories following the Vue Style Guide.

Dynamic Imports

To dynamically import a component (also known as lazy-loading a component) all you need to do is add the Lazy prefix to the component name.

layouts/default.vue

  1. <template>
  2. <div>
  3. <TheHeader />
  4. <Nuxt />
  5. <LazyTheFooter />
  6. </div>
  7. </template>

This is particularly useful if the component is not always needed. By using the Lazy prefix you can delay loading the component code until the right moment, which can be helpful for optimizing your JavaScript bundle size.

pages/index.vue

  1. <template>
  2. <div>
  3. <h1>Mountains</h1>
  4. <LazyMountainsList v-if="show" />
  5. <button v-if="!show" @click="show = true">Show List</button>
  6. </div>
  7. </template>
  8. <script>
  9. export default {
  10. data() {
  11. return {
  12. show: false
  13. }
  14. }
  15. }
  16. </script>

Cheatsheet