Компоненты

Исходники
Nuxt Kit предоставляет набор утилит, которые помогут вам работать с компонентами. Вы можете зарегистрировать компоненты глобально или локально, а также добавить директории для сканирования на наличие компонентов.

Компоненты - это строительные блоки вашего приложения Nuxt. Они представляют собой переиспользуемые инстансы Vue, которые могут быть использованы для создания пользовательского интерфейса. В Nuxt компоненты из директории components по умолчанию импортируются автоматически. Однако, если вам нужно импортировать компоненты из альтернативной директории или вы хотите выборочно импортировать их по мере необходимости, @nuxt/kit предоставляет методы addComponentsDir и addComponent. Эти утилиты позволяют настроить конфигурацию компонентов в соответствии с вашими потребностями.

Посмотрите видео от Vue School о внедрении компонентов.

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:

PropertyTypeRequiredDescription
pathstringtruePath (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.
patternstring | string[]falseAccept Pattern that will be run against specified path.
ignorestring[]falseIgnore patterns that will be run against specified path.
prefixstringfalsePrefix all matched components with this string.
pathPrefixbooleanfalsePrefix component name by its path.
enabledbooleanfalseIgnore scanning this directory if set to true.
prefetchbooleanfalseThese 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
preloadbooleanfalseThese 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
isAsyncbooleanfalseThis 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)falseA 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.
globalbooleanfalseIf enabled, registers components to be globally available.
islandbooleanfalseIf enabled, registers components as islands. You can read more about islands in <NuxtIsland/> component description.
watchbooleanfalseWatch specified path for changes, including file additions and file deletions.
extensionsstring[]falseExtensions supported by Nuxt builder.
transpile'auto' | booleanfalseTranspile specified path using build.transpile. If set to 'auto', it will set transpile: true if node_modules/ is in path.

opts

PropertyTypeRequiredDescription
prependbooleanfalseIf 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:

PropertyTypeRequiredDescription
namestringtrueComponent name.
filePathstringtruePath to the component.
pascalNamestringfalsePascal case component name. If not provided, it will be generated from the component name.
kebabNamestringfalseKebab case component name. If not provided, it will be generated from the component name.
exportstringfalseSpecify named or default export. If not provided, it will be set to 'default'.
shortPathstringfalseShort path to the component. If not provided, it will be generated from the component path.
chunkNamestringfalseChunk name for the component. If not provided, it will be generated from the component name.
prefetchbooleanfalseThese 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
preloadbooleanfalseThese 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
globalbooleanfalseIf enabled, registers component to be globally available.
islandbooleanfalseIf enabled, registers component as island. You can read more about islands in <NuxtIsland/> component description.
mode'client' | 'server' | 'all'falseThis options indicates if component should render on client, server or both. By default, it will render on both client and server.
prioritynumberfalsePriority 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',
    })
  },
})