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.vue
in 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>
Top comments (2)
Auto import make my app heavy?
No, it does not, Nuxt JS page code-splitting does the magic.
From Debbie O’Brien's explanation:
"This module parses your template and automatically includes the component in the file where you are using it such as a page, layout or even a component. Because Nuxt.js uses automatic code splitting to split your pages by default this module works perfect as it will only contain the components that are used on that page. Also, if you use a component in more than 2 pages, Nuxt.js will automatically create a shared chunk for them thanks to the magic of WebPack."
You can also read more here
nuxtjs.org/blog/improve-your-devel...