mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-11 08:33:53 +00:00
41 lines
973 B
Markdown
41 lines
973 B
Markdown
|
# State
|
||
|
|
||
|
Nuxt provides `useState` to create a globally shared state.
|
||
|
|
||
|
## `useState`
|
||
|
|
||
|
Within your pages, components and plugins you can use `useState`. It can be used to create your own store implementation.
|
||
|
You can think of it as a ssr-friendly ref that it's value will be hydrated (preserved) after Server-Side rendering and it is shared across all components.
|
||
|
|
||
|
|
||
|
### Usage
|
||
|
|
||
|
```js
|
||
|
useState(key: string)
|
||
|
```
|
||
|
|
||
|
* **key**: a unique key to ensure that data fetching can be properly de-duplicated across requests
|
||
|
|
||
|
### Example
|
||
|
|
||
|
In this example, we use a server-only plugin to find about request locale.
|
||
|
|
||
|
```ts [plugins/locale.server.ts]
|
||
|
import { defineNuxtPlugin, useState } from '#app'
|
||
|
|
||
|
export default defineNuxtPlugin((nuxt) => {
|
||
|
const locale = useState('locale')
|
||
|
locale.value = nuxt.ssrContext.req.headers['accept-language']?.split(',')[0]
|
||
|
})
|
||
|
```
|
||
|
|
||
|
```vue
|
||
|
<script setup>
|
||
|
const locale = useState('locale')
|
||
|
</script>
|
||
|
|
||
|
<template>
|
||
|
Current locale: {{ locale }}
|
||
|
</template>
|
||
|
```
|