Skip to content

Commit

Permalink
feat(docs) Перевод документации Composition API (#194)
Browse files Browse the repository at this point in the history
* feat(docs) Перевод документации Composition API

* [autofix.ci] apply automated fixes

* Update docs/6.bridge/5.nuxt3-compatible-api.md

Co-authored-by: Evgeniy Gromin <[email protected]>

* Update docs/6.bridge/5.nuxt3-compatible-api.md

Co-authored-by: Evgeniy Gromin <[email protected]>

* Update docs/6.bridge/5.nuxt3-compatible-api.md

Co-authored-by: Evgeniy Gromin <[email protected]>

---------

Co-authored-by: Ivan Bochkarev <[email protected]>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Evgeniy Gromin <[email protected]>
  • Loading branch information
4 people authored Jun 19, 2024
1 parent 998acd8 commit f09713c
Showing 1 changed file with 35 additions and 35 deletions.
70 changes: 35 additions & 35 deletions docs/6.bridge/5.nuxt3-compatible-api.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
---
title: New Composition API
description: Nuxt Bridge implements composables compatible with Nuxt 3.
title: Новый Composition API
description: Nuxt Bridge реализует композаблы, совместимые с Nuxt 3.
---

By migrating from `@nuxtjs/composition-api` to the Nuxt 3 compatible API, there will be less rewriting when migrating to Nuxt 3.
Путем миграции с `@nuxtjs/composition-api` на API, совместимое с Nuxt 3, количество необходимого переписывания кода при миграции на Nuxt 3 будет минимальным.

## `ssrRef` and `shallowSsrRef`
## `ssrRef` и `shallowSsrRef`

These two functions have been replaced with a new composable that works very similarly under the hood: `useState`.
Эти две функции были заменены на новый композабл, работающий похожим образом внутри: `useState`.

The key differences are that you must provide a _key_ for this state (which Nuxt generated automatically for `ssrRef` and `shallowSsrRef`), and that it can only be called within a Nuxt 3 plugin (which is defined by `defineNuxtPlugin`) or a component instance. (In other words, you cannot use [`useState`](/docs/api/composables/use-state) with a global/ambient context, because of the danger of shared state across requests.)
Основные отличия заключаются в том, что вы должны предоставить _key_ для этого состояния (который Nuxt генерировал автоматически для `ssrRef` и `shallowSsrRef`), и что она может быть вызвана только внутри плагина Nuxt 3 (который определяется с помощью `defineNuxtPlugin`) или экземпляра компонента. (То есть вы не можете использовать [`useState`](/docs/api/composables/use-state) с глобальным/окружающим контекстом, потому что существует опасность общего состояния между запросами.)

```diff
- import { ssrRef } from '@nuxtjs/composition-api'
Expand All @@ -22,17 +22,17 @@ The key differences are that you must provide a _key_ for this state (which Nuxt
console.log(ref1.value)
```

Because the state is keyed, you can access the same state from multiple locations, as long as you are using the same key.
Поскольку состояние задается ключом, вы можете получить доступ к одному и тому же состоянию из нескольких мест, если используете один и тот же ключ.

You can read more about how to use this composable in [the Nuxt 3 docs](/docs/api/composables/use-state).
Вы можете прочитать подробнее о том, как использовать этот композабл, [в документации](/docs/api/composables/use-state).

## `ssrPromise`

This function has been removed, and you will need to find an alternative implementation if you were using it. If you have a use case for `ssrPromise`, please let us know via a discussion.
Эта функция была удалена, и вам потребуется найти альтернативную реализацию, если вы ее использовали. Если у вас есть случай использования `ssrPromise`, пожалуйста, сообщите нам об этом через обсуждение.

## `onGlobalSetup`

This function has been removed, but its use cases can be met by using [`useNuxtApp`](/docs/api/composables/use-nuxt-app) or [`useState`](/docs/api/composables/use-state) within `defineNuxtPlugin`. You can also run any custom code within the `setup()` function of a layout.
Эта функция была удалена, но ее случаи использования могут быть решены путем использования [`useNuxtApp`](/docs/api/composables/use-nuxt-app) или [`useState`](/docs/api/composables/use-state) внутри `defineNuxtPlugin`. Вы также можете запускать любой настраиваемый код внутри функции `setup()` лейаута.

```diff
- import { onGlobalSetup } from '@nuxtjs/composition-api'
Expand All @@ -49,29 +49,29 @@ This function has been removed, but its use cases can be met by using [`useNuxtA

## `useStore`

In order to access Vuex store instance, you can use `useNuxtApp().$store`.
Для доступа к экземпляру хранилища Vuex вы можете использовать: `useNuxtApp().$store`.

```diff
- import { useStore } from '@nuxtjs/composition-api`
+ const { $store } = useNuxtApp()
```

## `useContext` and `withContext`
## `useContext` и `withContext`

You can access injected helpers using `useNuxtApp`.
Вы можете получить доступ к внедренным хелперам с помощью: `useNuxtApp`.

```diff
- import { useContext } from '@nuxtjs/composition-api`
+ const { $axios } = useNuxtApp()
```

::note
`useNuxtApp()` also provides a key called `nuxt2Context` which contains all the same properties you would normally access from Nuxt 2 context, but it's advised _not_ to use this directly, as it won't exist in Nuxt 3. Instead, see if there is another way to access what you need. (If not, please raise a feature request or discussion.)
`useNuxtApp()` также предоставляет ключ `nuxt2Context`, содержащий все те же свойства, к которым вы обычно обращаетесь из контекста Nuxt 2, но рекомендуется _не_ использовать его непосредственно, так как он не будет существовать в Nuxt 3. Вместо этого попробуйте найти другой способ получить доступ к тому, что вам нужно. (Если такого способа нет, пожалуйста, создайте запрос на новую функцию или обсуждение.)
::

## `wrapProperty`

This helper function is not provided any more but you can replace it with the following code:
Этот хелппер больше не предоставляется, но вы можете заменить ее следующим кодом:

```js
const wrapProperty = (property, makeComputed = true) => () => {
Expand All @@ -80,19 +80,19 @@ const wrapProperty = (property, makeComputed = true) => () => {
}
```

## `useAsync` and `useFetch`
## `useAsync` и `useFetch`

These two composables can be replaced with `useLazyAsyncData` and `useLazyFetch`, which are documented [in the Nuxt 3 docs](/docs/getting-started/data-fetching). Just like the previous `@nuxtjs/composition-api` composables, these composables do not block route navigation on the client-side (hence the 'lazy' part of the name).
Эти два композабла можно заменить на `useLazyAsyncData` и `useLazyFetch`, которые документированы в [документации Nuxt 3](/docs/getting-started/data-fetching). Подобно предыдущим композаблам `@nuxtjs/composition-api`, они не блокируют навигацию по маршрутам на клиенте (отсюда и 'lazy', как часть имени).

::important
Note that the API is entirely different, despite similar sounding names. Importantly, you should not attempt to change the value of other variables outside the composable (as you may have been doing with the previous `useFetch`).
Обратите внимание, что API полностью отличается, несмотря на схожее звучание имен. Важно, что вы не должны пытаться изменять значение других переменных вне композабла (как вы, возможно, делали раньше с `useFetch`).
::

::warning
The `useLazyFetch` must have been configured for [Nitro](/docs/bridge/nitro).
`useLazyFetch` должен быть настроен для [Nitro](/docs/bridge/nitro).
::

Migrating to the new composables from `useAsync`:
Миграция на новые композаблы с `useAsync`:

```diff
<script setup>
Expand All @@ -104,7 +104,7 @@ Migrating to the new composables from `useAsync`:
</script>
```

Migrating to the new composables from `useFetch`:
Миграция на новые композаблы с `useFetch`:

```diff
<script setup>
Expand All @@ -123,45 +123,45 @@ Migrating to the new composables from `useFetch`:

### `useMeta`

In order to interact with `vue-meta`, you may use `useNuxt2Meta`, which will work in Nuxt Bridge (but not Nuxt 3) and will allow you to manipulate your meta tags in a `vue-meta`-compatible way.
Для взаимодействия с `vue-meta` вы можете использовать `useNuxt2Meta`, который будет работать в Nuxt Bridge (но не в Nuxt 3) и позволит вам манипулировать вашими мета-тегами в соответствии с vue-meta.

```diff
<script setup>
- import { useMeta } from '@nuxtjs/composition-api'
useNuxt2Meta({
title: 'My Nuxt App',
title: 'Мое приложение Nuxt',
})
</script>
```

You can also pass in computed values or refs, and the meta values will be updated reactively:
Вы также можете передавать computed значения или refs, и мета-значения будут обновляться реактивно:

```ts
<script setup>
const title = ref('my title')
const title = ref('мой заголовок')
useNuxt2Meta({
title,
})
title.value = 'new title'
title.value = 'новый заголовок'
</script>
```

::note
Be careful not to use both `useNuxt2Meta()` and the Options API `head()` within the same component, as behavior may be unpredictable.
Будьте осторожны и не используйте одновременно `useNuxt2Meta()` и Options API `head()` в одном и том же компоненте, поскольку поведение может быть непредсказуемым.
::

Nuxt Bridge also provides a Nuxt 3-compatible meta implementation that can be accessed with the [`useHead`](/docs/api/composables/use-head) composable.
Nuxt Bridge также предоставляет реализацию мета-тегов, совместимую с Nuxt 3, которую можно получить с помощью композабла [`useHead`](/docs/api/composables/use-head).

```diff
<script setup>
- import { useMeta } from '@nuxtjs/composition-api'
useHead({
title: 'My Nuxt App',
title: 'Мое приложение Nuxt',
})
</script>
```

You will also need to enable it explicitly in your `nuxt.config`:
Вам также необходимо явно включить его в вашем `nuxt.config`:

```js
import { defineNuxtConfig } from '@nuxt/bridge'
Expand All @@ -172,9 +172,9 @@ export default defineNuxtConfig({
})
```

This [`useHead`](/docs/api/composables/use-head) composable uses `@unhead/vue` under the hood (rather than `vue-meta`) to manipulate your `<head>`. Accordingly, it is recommended not to use both the native Nuxt 2 `head()` properties as well as [`useHead`](/docs/api/composables/use-head) , as they may conflict.
Этот композабл [`useHead`](/docs/api/composables/use-head) использует `@unhead/vue` внутри (а не `vue-meta`) для манипулирования вашим `<head>`. Соответственно, рекомендуется не использовать одновременно нативные свойства `head()` Nuxt 2 и [`useHead`](/docs/api/composables/use-head), так как они могут конфликтовать.

For more information on how to use this composable, see [the Nuxt 3 docs](/docs/getting-started/seo-meta).
Для получения дополнительной информации о том, как использовать этот композабл, см. [документацию Nuxt 3](/docs/getting-started/seo-meta).

### Explicit Imports

Expand All @@ -189,9 +189,9 @@ const double = computed(() => count.value * 2)
</script>
```

### Disabling Auto-imports
### Отключение автоматического импорта

If you want to disable auto-importing composables and utilities, you can set `imports.autoImport` to `false` in the `nuxt.config` file.
Если вы хотите отключить автоматический импорт композаблов и утилит, вы можете установить `imports.autoImport` в `false` в файле `nuxt.config`.

```ts [nuxt.config.ts]
export default defineNuxtConfig({
Expand All @@ -201,4 +201,4 @@ export default defineNuxtConfig({
})
```

This will disable auto-imports completely but it's still possible to use [explicit imports](#explicit-imports) from `#imports`.
Это полностью отключит автоимпорт, но все еще будет возможно использовать [явные импорты](#explicit-imports) из `#imports`.

0 comments on commit f09713c

Please sign in to comment.