Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

docs(api): add useNuxtApp composable #6786

Merged
merged 26 commits into from
Aug 22, 2022
Merged
Changes from 1 commit
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
fb0ac02
docs(api): add useNuxtApp composable docs
Krutie Aug 19, 2022
a36996e
docs(api): fix linting issues
Krutie Aug 19, 2022
ad78b00
Merge branch 'nuxt:main' into docs/api-composable-use-nuxt-app
Krutie Aug 21, 2022
1474134
fix(docs): codeblocks
Krutie Aug 22, 2022
97e2f34
Update docs/content/3.api/1.composables/use-nuxt-app.md
pi0 Aug 22, 2022
4f67c03
Update docs/content/3.api/1.composables/use-nuxt-app.md
pi0 Aug 22, 2022
f7189f2
Update docs/content/3.api/1.composables/use-nuxt-app.md
pi0 Aug 22, 2022
6166eec
Update docs/content/3.api/1.composables/use-nuxt-app.md
pi0 Aug 22, 2022
be86ba0
Update docs/content/3.api/1.composables/use-nuxt-app.md
pi0 Aug 22, 2022
bad40ac
Update docs/content/3.api/1.composables/use-nuxt-app.md
pi0 Aug 22, 2022
4603101
Update docs/content/3.api/1.composables/use-nuxt-app.md
pi0 Aug 22, 2022
1e35140
Update docs/content/3.api/1.composables/use-nuxt-app.md
pi0 Aug 22, 2022
7e5a3ba
Update docs/content/3.api/1.composables/use-nuxt-app.md
pi0 Aug 22, 2022
82e91f8
Update docs/content/3.api/1.composables/use-nuxt-app.md
pi0 Aug 22, 2022
72af002
Update docs/content/3.api/1.composables/use-nuxt-app.md
pi0 Aug 22, 2022
bf2d2be
Update docs/content/3.api/1.composables/use-nuxt-app.md
pi0 Aug 22, 2022
483d779
Update docs/content/3.api/1.composables/use-nuxt-app.md
pi0 Aug 22, 2022
decaa0c
Update docs/content/3.api/1.composables/use-nuxt-app.md
pi0 Aug 22, 2022
4ac796e
Update docs/content/3.api/1.composables/use-nuxt-app.md
pi0 Aug 22, 2022
3deed14
Update docs/content/3.api/1.composables/use-nuxt-app.md
pi0 Aug 22, 2022
9ea602c
Update docs/content/3.api/1.composables/use-nuxt-app.md
pi0 Aug 22, 2022
51b8e08
Apply suggestions from code review
pi0 Aug 22, 2022
307510d
Merge branch 'main' into docs/api-composable-use-nuxt-app
pi0 Aug 22, 2022
d17bc1d
remove globalName from docs
pi0 Aug 22, 2022
83b8ad3
updates
pi0 Aug 22, 2022
059abaa
refactor ordering
pi0 Aug 22, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 64 additions & 79 deletions docs/content/3.api/1.composables/use-nuxt-app.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,87 +10,86 @@ You can use `useNuxtApp()` within composables, plugins and components.
</script>
```

`useNuxtApp()` exposes the following properties that you can use to extend and customize your app and share state, data and variables.
## Methods

## `isHydrating`
### `provide (name, value)`

**`type: boolean`**
`nuxtApp` is a runtime context that you can extend usingΒ [Nuxt plugins](https://v3.nuxtjs.org/guide/directory-structure/plugins). You can use the `provide` function to create Nuxt plugins to make values and helper methods available in your Nuxt application across all composables and components.

You can use `nuxtApp.isHydrating` to check if the Nuxt app is hydrating on the client side.
`provide` function accepts `name` and `value` parameters.

### Example
**Example:**

```ts [components/nuxt-error-boundary.ts]
export default defineComponent({
setup (_props, { slots, emit }) {
const nuxtApp = useNuxtApp()
onErrorCaptured((err) => {
if (process.client && !nuxtApp.isHydrating) {
// ...
}
})
}
})
```
```js
const nuxtApp = useNuxtApp()
nuxtApp.provide('hello', (name) => `Hello ${name}!`)

## `vueApp`
// Prints "Hello name!"
console.log(nuxtApp.$hello('name'))
```

`vueApp` is the global Vue.js [application instance](https://vuejs.org/api/application.html#application-api) that you can access through `nuxtApp`. Some useful methods:
As you can see in the example above, `$hello` has become the new and custom part of `nuxtApp` context and it is available in all places where `nuxtApp` is accessible.

- **component()** - Registers a global component if passing both a name string and a component definition, or retrieves an already registered one if only the name is passed ([Read More](https://vuejs.org/api/application.html#app-component)).
- **directive()** - Registers a global custom directive if passing both a name string and a directive definition, or retrieves an already registered one if only the name is passed. ([Read More](https://vuejs.org/api/application.html#app-directive), [Example](https://v3.nuxtjs.org/guide/directory-structure/plugins#vue-directives)).
- **use()** - Installs aΒ **[Vue.js Plugin](https://vuejs.org/guide/reusability/plugins.html)**. ([Read More](https://vuejs.org/api/application.html#app-use), [Example](https://v3.nuxtjs.org/guide/directory-structure/plugins#vue-plugins))
### `hook(name, cb)`

:ReadMore{link="https://vuejs.org/api/application.html#application-api"}
Hooks available in `nuxtApp` allows you to customize the runtime aspects of your Nuxt application. You can use runtime hooks in Vue.js composables and [Nuxt plugins](/guide/directory-structure/plugins) to hook into the rendering lifecycle.

## `ssrContext`
`hook` function is useful for adding custom logic by hooking into the rendering lifecycle at a specific point. `hook` function is mostly used when creating Nuxt plugins.

`ssrContext` is generated during server-side rendering and it is only available on the server side. Nuxt exposes the following properties through `ssrContext`:
See [Runtime Hooks](/api/advanced/hooks#app-hooks-runtime) for avialble runtime hooks called by Nuxt.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pi0 little typo: avialble

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for the notice. (please check your discord when could. I've sent a message)


pi0 marked this conversation as resolved.
Show resolved Hide resolved
- **`url`** (string) - Current request url.
- **`event`** ([unjs/h3](https://github.com/unjs/h3) Request event) - Access to `req` and `res` objects for the current request.
- **`payload`** - NuxtApp payload object.
```js [plugins/test.ts]
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.hook('page:start', () => {
/* your code goes here */
})
nuxtApp.hook('vue:error', (..._args) => {
console.log('vue:error')
// if (process.client) {
// console.log(..._args)
// }
})
})
```

## `provide(name, value)`
### `callhook(name, ...args)`

`nuxtApp` is a runtime context that you can extend usingΒ [Nuxt plugins](https://v3.nuxtjs.org/guide/directory-structure/plugins). You can use the `provide` function to create Nuxt plugins to make values and helper methods available in your Nuxt application across all composables and components.
`callHook` returns a promise when called with any of the existing hooks.

`provide` function accepts `name` and `value` parameters.
```js
await nuxtApp.callHook('my-plugin:init')
```

### Example
## Properties

```js
const nuxtApp = useNuxtApp()
nuxtApp.provide('hello', (name) => `Hello ${name}!`)
`useNuxtApp()` exposes the following properties that you can use to extend and customize your app and share state, data and variables.

// Prints "Hello name!"
console.log(nuxtApp.$hello('name'))
```
### `vueApp`

As you can see in the example above, `$hello` has become the new and custom part of `nuxtApp` context and it is available in all places where `nuxtApp` is accessible.
`vueApp` is the global Vue.js [application instance](https://vuejs.org/api/application.html#application-api) that you can access through `nuxtApp`. Some useful methods:

## State and variables
- [**component()**](https://vuejs.org/api/application.html#app-component) - Registers a global component if passing both a name string and a component definition, or retrieves an already registered one if only the name is passed.
- [**directive()**](https://vuejs.org/api/application.html#app-directive) - Registers a global custom directive if passing both a name string and a directive definition, or retrieves an already registered one if only the name is passed[(example)](https://v3.nuxtjs.org/guide/directory-structure/plugins#vue-directives).
- [**use()**](https://vuejs.org/api/application.html#app-use) - Installs aΒ **[Vue.js Plugin](https://vuejs.org/guide/reusability/plugins.html)** [(example)](https://v3.nuxtjs.org/guide/directory-structure/plugins#vue-plugins).

### `$config`
:ReadMore{link="https://vuejs.org/api/application.html#application-api"}

`nuxtApp.$config` exposes a runtime config and environment variables on the client side to the Nuxt app context through two keys: `app` and `public`.
### `ssrContext`

Keys found under `app` and `public` are available on the client side.
`ssrContext` is generated during server-side rendering and it is only available on the server side. Nuxt exposes the following properties through `ssrContext`:

- **app:**
- **baseURL** - `type: string`
- **buildAssetsDir** - `type: string`
- **cdnURL** - `type: string`
- **public** - `nuxtApp.$config.public` allows you to access the public runtime config that is set in the `nuxt.config` file of your Nuxt app.
- **`url`** (string) - Current request url.
- **`event`** ([unjs/h3](https://github.com/unjs/h3) request event) - Access to `req` and `res` objects for the current request.
- **`payload`** (object) - NuxtApp payload object.

### `payload`

`payload` exposes data and state variables from server side to client side and makes them available in the `window.NUXT` object that is accessible from the browser.
`payload` exposes data and state variables from server side to client side and makes them available in the `window.__NUXT__` object that is accessible from the browser.

`payload` exposes the following keys on the client side after they are stringified and passed from the server side:

- **serverRendered** - `type: boolean`
- **data** - `type: record object` - When you fetch the data from an API endpoint using either `useFetch` or `useAsyncData`, resulting payload can be accessed from the `payload.data`. This data is cached and helps you prevent fetching the same data in case an identical request is made more than once.
- **serverRendered** (boolean) - Indicates if response is server-side-rendered.
- **data** (object) - When you fetch the data from an API endpoint using either `useFetch` or `useAsyncData`, resulting payload can be accessed from the `payload.data`. This data is cached and helps you prevent fetching the same data in case an identical request is made more than once.

```vue [app.vue]
export default defineComponent({
Expand All @@ -104,7 +103,7 @@ After fetching the value of `count` using `useAsyncData` in the example above, i

When accessing the same `payload.data` from [ssrcontext](#ssrcontext), you can access the same value on the server side as well.

- **state** - `type: record object` - When you use `useState` composable in Nuxt to set shared state, this state data is accessed through `payload.state.[name-of-your-state]`.
- **state** (object) - When you use `useState` composable in Nuxt to set shared state, this state data is accessed through `payload.state.[name-of-your-state]`.

```js [plugins/my-plugin.ts]
export const useColor = () => useState<string>('color', () => 'pink')
Expand All @@ -116,35 +115,21 @@ export default defineNuxtPlugin((nuxtApp) => {
})
```

- **config** - Same as the [$config](#config) section above.


### `hook(name, cb)`
### `isHydrating`

Hooks available in `nuxtApp` allows you to customize the runtime aspects of your Nuxt application. You can use runtime hooks in Vue composable and [Nuxt plugins](/guide/directory-structure/plugins) to hook into the rendering lifecycle.
You can use `nuxtApp.isHydrating` (boolean) to check if the Nuxt app is hydrating on the client side.

`hook` function is useful for adding custom logic by hooking into the rendering lifecycle at a specific point. `hook` function is mostly used when creating Nuxt plugins.
**Example:**

```js [plugins/test.ts]
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.hook('page:start', () => {
/* your code goes here */
})
nuxtApp.hook('vue:error', (..._args) => {
console.log('vue:error')
// if (process.client) {
// console.log(..._args)
// }
})
```ts [components/nuxt-error-boundary.ts]
export default defineComponent({
setup (_props, { slots, emit }) {
const nuxtApp = useNuxtApp()
onErrorCaptured((err) => {
if (process.client && !nuxtApp.isHydrating) {
// ...
}
})
}
})
```

See [Runtime Hooks](/api/advanced/hooks#app-hooks-runtime) for avialble runtime hooks called by Nuxt.

### `callhook(name, ...args)`

`callHook` returns a promise when called with any of the existing hooks.

```js
await nuxtApp.callHook('my-plugin:init')
```