Nuxt 3 已于 31 July 2026 结束生命周期
此版本将不再接收错误修复或安全补丁。 升级到 Nuxt 4 或获取 HeroDevs 提供的延长支持

状态管理

Nuxt 提供强大的状态管理库和 `useState` 组合函数,用于创建响应式且支持 SSR 的共享状态。

Geprüfte Übersetzung ·0 % geprüft

Nuxt 提供 useState 组合函数,用于在组件间创建响应式且支持 SSR 的共享状态。

useState 是支持 SSR 的 ref 替代方案。其值会在服务器端渲染后(客户端水合期间)保留,并通过唯一键在所有使用它的组件间共享。

由于 useState 中的数据会被序列化为 JSON,因此请勿在其中包含无法序列化的内容,例如类、函数或符号。
详细了解 useState 组合函数。

最佳实践

切勿在 <script setup> 或 setup() 函数之外定义 const state = ref()。
例如,执行 export myState = ref({}) 会导致状态在服务器请求间共享,可能引发内存泄漏。
应使用 const useX = () => useState('x')

示例

基本用法

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

<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>
Read and edit a live example in Docs > Examples > Features > State Management.
如需全局使缓存状态失效,请参阅 clearNuxtState 工具。

初始化状态

大多数情况下,您会想要使用异步解析的数据来初始化状态。您可以使用 app.vue 组件和 callOnce 工具来实现。

<script setup lang="ts">
const websiteConfig = useState('config')

await callOnce(async () => {
  websiteConfig.value = await $fetch('https://my-cms.com/api/website-config')
})
</script>
这与 Nuxt 2 中的 nuxtServerInit action 类似,允许您在渲染页面前于服务器端填充存储的初始状态。
Weitere Informationen findest du unter Docs > API > Utils > Call Once.

与 Pinia 配合使用

在此示例中,我们利用 Pinia 模块 创建一个全局存储,并在应用中使用它。

确保通过 npx nuxt module add pinia 安装 Pinia 模块,或遵循模块安装步骤。
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
    },
  },
})

高级用法

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)))
}
Read and edit a live example in Docs > Examples > Advanced > Locale.

共享状态

通过自动导入的组合函数,我们可以定义全局类型安全的状态,并在应用中导入使用。

export const useColor = () => useState<string>('color', () => 'pink')
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>

使用第三方库

Nuxt 曾依赖 Vuex 库来提供全局状态管理。如果您要从 Nuxt 2 迁移,请参阅迁移指南。

Nuxt 对状态管理不持特定观点,您可以自由选择适合自己需求的解决方案。现有多种与流行状态管理库的集成,包括:

  • Pinia - Vue 官方推荐
  • Harlem - 不可变全局状态管理
  • XState - 状态机方案,带有用于可视化和测试状态逻辑的工具