---
title: "状态管理"
description: "Nuxt 提供强大的状态管理库和 useState 可组合函数以创建响应式且为 SSR 友好的共享状态。"
canonical_url: "https://nuxt.zhcndoc.com/docs/4.x/getting-started/state-management"
---
# 状态管理

> Nuxt 提供强大的状态管理库和 useState 可组合函数以创建响应式且为 SSR 友好的共享状态。

Nuxt 提供 [`useState`](https://nuxt.zhcndoc.com/docs/4.x/api/composables/use-state) 可组合函数，用于创建响应式且对 SSR 友好的状态，并在多个组件之间共享。

[`useState`](https://nuxt.zhcndoc.com/docs/4.x/api/composables/use-state) 是对 SSR 友好的 [`ref`](https://vuejs.org/api/reactivity-core#ref) 替代方案。它的值会在服务器端渲染后（客户端 hydration 期间）保留，并通过唯一键在所有使用它的组件之间共享。

::video-accordion{title="观看 Alexander Lichter 的视频，了解为何以及何时使用 useState" videoId="mv0WcBABcIk"}
::

::important
由于 [`useState`](https://nuxt.zhcndoc.com/docs/4.x/api/composables/use-state) 中的数据会被序列化为 JSON，因此请确保其中不包含无法序列化的内容，例如类、函数或符号。
::

::read-more{to="https://nuxt.zhcndoc.com/docs/4.x/api/composables/use-state"}
进一步了解 `useState` 可组合函数。
::

## 最佳实践

::warning
切勿在 `<script setup>` 或 `setup()` 函数之外定义 `const state = ref()`。<br>
例如，执行 `export myState = ref({})` 会导致在服务器上的请求之间共享状态，并可能导致内存泄漏。
::

::tip{icon="i-lucide-circle-check"}
应改为使用 `const useX = () => useState('x')`
::

## 示例

### 基本用法

在此示例中，我们使用组件本地的计数器状态。任何其他使用 `useState('counter')` 的组件都会共享相同的响应式状态。

```vue twoslash [app/app.vue]
<script setup lang="ts">
const counter = useState('counter', () => Math.round(Math.random() * 1000))
</script>

<template>
  <div>
    计数器：{{ counter }}
    <button @click="counter++">
      +
    </button>
    <button @click="counter--">
      -
    </button>
  </div>
</template>
```

::link-example{to="https://nuxt.zhcndoc.com/docs/examples/features/state-management"}
::

::note
若要全局清除缓存状态，请参阅 [`clearNuxtState`](https://nuxt.zhcndoc.com/docs/4.x/api/utils/clear-nuxt-state) 工具函数。
::

### 初始化状态

大多数情况下，你会希望使用异步解析的数据来初始化状态。你可以使用 [`app.vue`](https://nuxt.zhcndoc.com/docs/4.x/directory-structure/app/app) 组件和 [`callOnce`](https://nuxt.zhcndoc.com/docs/4.x/api/utils/call-once) 工具函数来实现。

```vue twoslash [app/app.vue]
<script setup lang="ts">
const websiteConfig = useState('config')

await callOnce(async () => {
  websiteConfig.value = await $fetch('https://my-cms.com/api/website-config')
})
</script>
```

::tip
这类似于 Nuxt 2 中的 [`nuxtServerInit` action](https://v2.nuxt.com/docs/directory-structure/store/#the-nuxtserverinit-action)，它允许在服务器端渲染页面之前填充 store 的初始状态。
::

::read-more{to="https://nuxt.zhcndoc.com/docs/4.x/api/utils/call-once"}
::

### 与 Pinia 一起使用

在此示例中，我们利用 [Pinia 模块](https://nuxt.zhcndoc.com/modules/pinia) 创建一个全局 store 并在应用中使用它。

::important
请确保使用 `npx nuxt module add pinia` 安装 Pinia 模块，或遵循该模块的[安装步骤](https://pinia.vuejs.org/ssr/nuxt.html#Installation)。
::

::code-group
```ts [app/stores/website.ts]
export const useWebsiteStore = defineStore('websiteStore', {
  state: () => ({
    name: '',
    description: '',
  }),
  actions: {
    async fetch () {
      const infos = await $fetch('https://api.nuxt.com/modules/pinia')

      this.name = infos.name
      this.description = infos.description
    },
  },
})
```

```vue [app/app.vue]
<script setup lang="ts">
const website = useWebsiteStore()

await callOnce(website.fetch)
</script>

<template>
  <main>
    <h1>{{ website.name }}</h1>
    <p>{{ website.description }}</p>
  </main>
</template>
```
::

## 高级用法

::code-group
```ts [app/composables/locale.ts]
import type { Ref } from 'vue'

export const useLocale = () => {
  return useState<string>('locale', () => useDefaultLocale().value)
}

export const useDefaultLocale = (fallback = 'en-US') => {
  const locale = ref(fallback)
  if (import.meta.server) {
    const reqLocale = useRequestHeaders()['accept-language']?.split(',')[0]
    if (reqLocale) {
      locale.value = reqLocale
    }
  } else if (import.meta.client) {
    const navLang = navigator.language
    if (navLang) {
      locale.value = navLang
    }
  }
  return locale
}

export const useLocales = () => {
  const locale = useLocale()
  const locales = ref([
    'en-US',
    'en-GB',
    // ...,
    'ja-JP-u-ca-japanese',
  ])
  if (!locales.value.includes(locale.value)) {
    locales.value.unshift(locale.value)
  }
  return locales
}

export const useLocaleDate = (date: Ref<Date> | Date, locale = useLocale()) => {
  return computed(() => new Intl.DateTimeFormat(locale.value, { dateStyle: 'full' }).format(unref(date)))
}
```

```vue [app/app.vue]
<script setup lang="ts">
const locales = useLocales()
const locale = useLocale()
const date = useLocaleDate(new Date('2016-10-26'))
</script>

<template>
  <div>
    <h1>Nuxt 生日</h1>
    <p>{{ date }}</p>
    <label for="locale-chooser">预览不同的区域设置</label>
    <select
      id="locale-chooser"
      v-model="locale"
    >
      <option
        v-for="loc of locales"
        :key="loc"
        :value="loc"
      >
        {{ loc }}
      </option>
    </select>
  </div>
</template>
```
::

::link-example{to="https://nuxt.zhcndoc.com/docs/examples/advanced/locale"}
::

## 共享状态

通过使用[自动导入的可组合函数](https://nuxt.zhcndoc.com/docs/4.x/directory-structure/app/composables)，我们可以定义全局类型安全状态，并在整个应用中导入这些状态。

```ts twoslash [composables/states.ts]
export const useColor = () => useState<string>('color', () => 'pink')
```

```vue [app/app.vue]
<script setup lang="ts">
// ---cut-start---
const useColor = () => useState<string>('color', () => 'pink')
// ---cut-end---
const color = useColor() // 与 useState('color') 相同
</script>

<template>
  <p>当前颜色：{{ color }}</p>
</template>
```

::video-accordion{title="观看 Daniel Roe 的视频，了解如何在 Nuxt 中处理全局状态与 SSR" videoId="dZSNW07sO-A"}
::

## 使用第三方库

Nuxt **曾依赖** Vuex 库来提供全局状态管理。如果你正在从 Nuxt 2 迁移，请参阅[迁移指南](https://nuxt.zhcndoc.com/docs/4.x/migration/configuration#vuex)。

Nuxt 对状态管理并不强制使用特定方案，因此请根据您的需求自由选择合适的解决方案。下面是与一些流行状态管理库的集成：

- [Pinia](https://nuxt.zhcndoc.com/modules/pinia) - Vue 官方推荐
- [Harlem](https://nuxt.zhcndoc.com/modules/harlem) - 不可变的全局状态管理
- [XState](https://nuxt.zhcndoc.com/modules/xstate) - 使用状态机的方法，并提供用于可视化和测试状态逻辑的工具


## Sitemap

See the full [sitemap](https://nuxt.zhcndoc.com/sitemap.md) for all pages.
