loading...

Use @nuxt/components to automatically import components!

ryosh profile image ryosh ・1 min read

What's @nuxt/components

This is a module that automatically imports components in Nuxt.js development.
You can omit the definition of the import statement and the components field.
https://github.com/nuxt/component

Examples

Follow the USAGE in the README.
https://github.com/nuxt/components#usage

Normally, you need to import a component to use it.

<template>
  <div>
    <ComponentFoo />
  </div>
</template>
<script>
import ComponentFoo from '~/components/ComponentFoo.vue'

export default {
  components: {
    ComponentFoo
  }
}
</script>

but with @nuxt/components, you don't need to specify the import in <script>.

<template>
  <div>
    <ComponentFoo />
  </div>
</template>

In the case of dynamic components

Put Lazy at the beginning of a component.

<template>
  <div>
    <LazyComponentFoo v-if='foo' />
    <button @click='loadFoo'>Load Foo</button>
  </div>
</template>

<script>
export default {
  data () {
    return {
      foo: null
    }
  },
  methods: {
    async loadFoo () {
      this.foo = await this.getFoo()
    },
    getFoo () {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve('foo');
        }, 2000);
      });
    }
  }
}
</script>

In the case of a nested the same name component

For example, if there is the same name component Bar.vuein a different directory, such as the following.

components/
  Bar.vue
  foo/
    Bar.vue

Add the following to nuxt.config.js.

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

Components under foo/ are prefixed with Foo.

<template>
  <div>
    // components/Bar.vue
    <Bar />
    // components/foo/Bar.vue
    <FooBar />
  </div>
</template>

reference

https://github.com/nuxt/components

Posted on by:

ryosh profile

ryosh

@ryosh

I'm a Front End Engineer who build product which SPA web application in Nuxt.js and Django REST framework.

Discussion

markdown guide