Skip to content

Commit

Permalink
feat(docs): translate docs/2.guide/2.directory-structure/1.composable…
Browse files Browse the repository at this point in the history
…s.md (#39) (#201)

Signed-off-by: Evgeniy Gromin <[email protected]>
  • Loading branch information
JonikUl authored Jun 21, 2024
1 parent 696eda9 commit 63cdc83
Showing 1 changed file with 27 additions and 27 deletions.
54 changes: 27 additions & 27 deletions docs/2.guide/2.directory-structure/1.composables.md
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
---
title: 'composables'
head.title: 'composables/'
description: Use the composables/ directory to auto-import your Vue composables into your application.
description: Используйте директорию composables/ для автоматического импорта композаблов Vue в ваше приложение.
navigation.icon: i-ph-folder-duotone
---

## Использование

**Method 1:** Using named export
**Метод 1:** Использование именованного экспорта

```js [composables/useFoo.ts]
export const useFoo = () => {
return useState('foo', () => 'bar')
}
```

**Method 2:** Using default export
**Метод 2:** Использование экспорта по умолчанию

```js [composables/use-foo.ts or composables/useFoo.ts]
// It will be available as useFoo() (camelCase of file name without extension)
// Композабл будет доступен как useFoo() (camelCase имени файла без расширения)
export default function () {
return useState('foo', () => 'bar')
}
```

**Usage:** You can now use auto imported composable in `.js`, `.ts` and `.vue` files
**Использование:** Теперь вы можете использовать автоматически импортируемый композабл в файлах `.js`, `.ts` и `.vue`

```vue [app.vue]
<script setup lang="ts">
Expand All @@ -39,28 +39,28 @@ const foo = useFoo()
```

::alert{type=info}
The `composables/` directory in Nuxt does not provide any additional reactivity capabilities to your code. Instead, any reactivity within composables is achieved using Vue's Composition API mechanisms, such as ref and reactive. Note that reactive code is also not limited to the boundaries of the `composables/` directory. You are free to employ reactivity features wherever they're needed in your application.
Директория `composables/` в Nuxt не предоставляет никаких дополнительных возможностей реактивности для вашего кода. Вместо этого любая реактивность в композаблах достигается с помощью механизмов Composition API из Vue, таких как ref и reactive. Обратите внимание, что реактивный код также не ограничен границами директории `composables/`. Вы можете свободно использовать функции реактивности везде, где они необходимы в приложении.
::

:read-more{to="/docs/guide/concepts/auto-imports"}

:link-example{to="/docs/examples/features/auto-imports"}

## Types
## Типы

Under the hood, Nuxt auto generates the file `.nuxt/imports.d.ts` to declare the types.
Под капотом Nuxt автоматически генерирует файл `.nuxt/imports.d.ts` для объявления типов.

Be aware that you have to run [`nuxi prepare`](/docs/api/commands/prepare), [`nuxi dev`](/docs/api/commands/dev) or [`nuxi build`](/docs/api/commands/build) in order to let Nuxt generate the types.
Имейте в виду, что вам необходимо запустить [`nuxi prepare`](/docs/api/commands/prepare), [`nuxi dev`](/docs/api/commands/dev) или [`nuxi build`](/docs/api/commands/build), чтобы позволить Nuxt сгенерировать типы.

::note
If you create a composable without having the dev server running, TypeScript will throw an error, such as `Cannot find name 'useBar'.`
Если вы создаете композабл без запущенного сервера разработки, TypeScript выдаст ошибку, такую как `Cannot find name 'useBar'.`.
::

## Примеры

### Nested Composables
### Вложенные композаблы

You can use a composable within another composable using auto imports:
Вы можете использовать один композабл внутри другого с помощью автоматического импорта:

```js [composables/test.ts]
export const useFoo = () => {
Expand All @@ -69,9 +69,9 @@ export const useFoo = () => {
}
```

### Access plugin injections
### Доступ к внедренным плагинам

You can access [plugin injections](/docs/guide/directory-structure/plugins#automatically-providing-helpers) from composables:
Вы можете получить доступ к [внедренным плагинам](/docs/guide/directory-structure/plugins#automatically-providing-helpers) из композаблов:

```js [composables/test.ts]
export const useHello = () => {
Expand All @@ -80,40 +80,40 @@ export const useHello = () => {
}
```

## How Files Are Scanned
## Как сканируются файлы

Nuxt only scans files at the top level of the [`composables/` directory](/docs/guide/directory-structure/composables), e.g.:
Nuxt сканирует только файлы на верхнем уровне директории [`composables/`](/docs/guide/directory-structure/composables), например:

```bash [Directory Structure]
| composables/
---| index.ts // scanned
---| useFoo.ts // scanned
---| index.ts // сканируется
---| useFoo.ts // сканируется
-----| nested/
-------| utils.ts // not scanned
-------| utils.ts // не сканируется
```

Only `composables/index.ts` and `composables/useFoo.ts` would be searched for imports.
Поиск импорта будет выполняться только в `composables/index.ts` и `composables/useFoo.ts`.

To get auto imports working for nested modules, you could either re-export them (recommended) or configure the scanner to include nested directories:
Чтобы автоматический импорт работал для вложенных модулей, вы можете либо повторно экспортировать их (рекомендуется), либо настроить сканер для включения вложенных директорий:

**Пример:** Re-export the composables you need from the `composables/index.ts` file:
**Пример:** Повторно экспортируйте необходимые вам композаблы из файла `composables/index.ts`:

```ts [composables/index.ts]
// Enables auto import for this export
// Включает автоматический импорт для этого экспорта
export { utils } from './nested/utils.ts'
```

**Пример:** Scan nested directories inside the `composables/` folder:
**Пример:** Сканировать вложенные директории внутри `composables/`:

```ts twoslash [nuxt.config.ts]
export default defineNuxtConfig({
imports: {
dirs: [
// Scan top-level modules
// Сканирование модулей верхнего уровня
'composables',
// ... or scan modules nested one level deep with a specific name and file extension
// ... или сканировать модули, вложенные на один уровень глубже с определенным именем и расширением файла
'composables/*/index.{ts,js,mjs,mts}',
// ... or scan all modules within given directory
// ... или сканировать все модули в указанной директории
'composables/**'
]
}
Expand Down

0 comments on commit 63cdc83

Please sign in to comment.