Компоненты
Компоненты - это строительные блоки вашего приложения Nuxt. Они представляют собой переиспользуемые инстансы Vue, которые могут быть использованы для создания пользовательского интерфейса. В Nuxt компоненты из директории components по умолчанию импортируются автоматически. Однако, если вам нужно импортировать компоненты из альтернативной директории или вы хотите выборочно импортировать их по мере необходимости, @nuxt/kit предоставляет методы addComponentsDir и addComponent. Эти утилиты позволяют настроить конфигурацию компонентов в соответствии с вашими потребностями.
addComponentsDir
Регистрирует директорию, которая будет сканироваться на наличие компонентов и импортироваться только при использовании. Помните, что при этом не происходит глобальной регистрации компонентов, пока вы не укажете опцию global: true.
Usage
export default defineNuxtModule({
meta: {
name: '@nuxt/ui',
configKey: 'ui',
},
setup() {
addComponentsDir({
path: resolve('./runtime/components'),
prefix: 'U',
pathPrefix: false
})
}
})
Type
function addComponentsDir (dir: ComponentsDir, opts: { prepend?: boolean } = {}): void
Параметры
dir An object with the following properties:
| Property | Type | Required | Description |
|---|---|---|---|
path | string | true | Path (absolute or relative) to the directory containing your components. You can use Nuxt aliases (~ or @) to refer to directories inside project or directly use an npm package path similar to require. |
pattern | string | string[] | false | Accept Pattern that will be run against specified path. |
ignore | string[] | false | Ignore patterns that will be run against specified path. |
prefix | string | false | Prefix all matched components with this string. |
pathPrefix | boolean | false | Prefix component name by its path. |
enabled | boolean | false | Ignore scanning this directory if set to true. |
prefetch | boolean | false | These properties (prefetch/preload) are used in production to configure how components with Lazy prefix are handled by webpack via its magic comments. Learn more on webpack documentation |
preload | boolean | false | These properties (prefetch/preload) are used in production to configure how components with Lazy prefix are handled by webpack via its magic comments. Learn more on webpack documentation |
isAsync | boolean | false | This flag indicates, component should be loaded async (with a separate chunk) regardless of using Lazy prefix or not. |
extendComponent | (component: Component) => Promise<Component | void> | (Component | void) | false | A function that will be called for each component found in the directory. It accepts a component object and should return a component object or a promise that resolves to a component object. |
global | boolean | false | If enabled, registers components to be globally available. |
island | boolean | false | If enabled, registers components as islands. You can read more about islands in <NuxtIsland/> component description. |
watch | boolean | false | Watch specified path for changes, including file additions and file deletions. |
extensions | string[] | false | Extensions supported by Nuxt builder. |
transpile | 'auto' | boolean | false | Transpile specified path using build.transpile. If set to 'auto', it will set transpile: true if node_modules/ is in path. |
opts
| Property | Type | Required | Description |
|---|---|---|---|
prepend | boolean | false | If set to true, the directory will be prepended to the array with unshift() instead of push(). |
addComponent
Регистрирует компонент для автоматического импорта.
Usage
import { defineNuxtModule, createResolver, addComponent } from '@nuxt/kit'
export default defineNuxtModule({
meta: {
name: '@nuxt/image',
configKey: 'image',
},
async setup() {
const resolver = createResolver(import.meta.url)
addComponent({
name: 'NuxtImg',
filePath: resolver.resolve('./runtime/components/NuxtImg.vue'),
})
addComponent({
name: 'NuxtPicture',
filePath: resolver.resolve('./runtime/components/NuxtPicture.vue'),
})
},
})
Type
function addComponent (options: AddComponentOptions): void
Параметры
options: An object with the following properties:
| Property | Type | Required | Description |
|---|---|---|---|
name | string | true | Component name. |
filePath | string | true | Path to the component. |
pascalName | string | false | Pascal case component name. If not provided, it will be generated from the component name. |
kebabName | string | false | Kebab case component name. If not provided, it will be generated from the component name. |
export | string | false | Specify named or default export. If not provided, it will be set to 'default'. |
shortPath | string | false | Short path to the component. If not provided, it will be generated from the component path. |
chunkName | string | false | Chunk name for the component. If not provided, it will be generated from the component name. |
prefetch | boolean | false | These properties (prefetch/preload) are used in production to configure how components with Lazy prefix are handled by webpack via its magic comments. Learn more on webpack documentation |
preload | boolean | false | These properties (prefetch/preload) are used in production to configure how components with Lazy prefix are handled by webpack via its magic comments. Learn more on webpack documentation |
global | boolean | false | If enabled, registers component to be globally available. |
island | boolean | false | If enabled, registers component as island. You can read more about islands in <NuxtIsland/> component description. |
mode | 'client' | 'server' | 'all' | false | This options indicates if component should render on client, server or both. By default, it will render on both client and server. |
priority | number | false | Priority of the component, if multiple components have the same name, the one with the highest priority will be used. |
Examples
If you want to auto-import a component from an npm package, and the component is a named export (rather than the default), you can use the export option to specify it.
import { addComponent, defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup () {
// import { MyComponent as MyAutoImportedComponent } from 'my-npm-package'
addComponent({
name: 'MyAutoImportedComponent',
export: 'MyComponent',
filePath: 'my-npm-package',
})
},
})