状态管理

Nuxt 提供了强大的状态管理库和 useState 可组合项,用于创建响应式且支持服务器端渲染 (SSR) 的共享状态。

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

¥Nuxt provides the useState composable to create a reactive and SSR-friendly shared state across components.

useState 是支持服务器渲染 (SSR) 的 ref 替代品。它的值将在服务器端渲染(客户端 hydration 期间)后保留,并使用唯一键在所有组件之间共享。

¥useState is an SSR-friendly ref replacement. Its value will be preserved after server-side rendering (during client-side hydration) and shared across all components using a unique key.

由于 useState 中的数据将被序列化为 JSON,因此务必确保它不包含任何无法序列化的内容,例如类、函数或符号。

:

Read more in Docs > API > Composables > Use State.

阅读更多关于 useState 可组合项的内容。

¥Read more about useState composable.

::

最佳实践

¥Best Practices

切勿在 <script setup>setup() 函数之外定义 const state = ref()
例如,执行 export myState = ref({}) 将导致服务器请求之间状态共享,并可能导致内存泄漏。¥Never define const state = ref() outside of <script setup> or setup() function.
For example, doing export myState = ref({}) would result in state shared across requests on the server and can lead to memory leaks.
请使用 const useX = () => useState('x')¥Instead use const useX = () => useState('x')

示例

¥Examples

基本用法

¥Basic Usage

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

¥In this example, we use a component-local counter state. Any other component that uses useState('counter') shares the same reactive state.

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

<template>
  <div>
    Counter: {{ counter }}
    <button @click="counter++">
      +
    </button>
    <button @click="counter--">
      -
    </button>
  </div>
</template>
Read and edit a live example in Docs > Examples > Features > State Management.
要全局使缓存状态无效,请参阅 clearNuxtState 实用程序。

初始化状态

¥Initializing State

大多数时候,你需要使用异步解析的数据来初始化状态。你可以将 app.vue 组件与 callOnce 实用程序结合使用来实现此目的。

¥Most of the time, you will want to initialize your state with data that resolves asynchronously. You can use the app.vue component with the callOnce util to do so.

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>
这类似于 Nuxt 2 中的 nuxtServerInit action,它允许在渲染页面之前填充商店服务器端的初始状态。
Read more in Docs > API > Utils > Call Once.

与 Pinia 一起使用

¥Usage with Pinia

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

¥In this example, we leverage the Pinia module to create a global store and use it across the app.

确保安装带有 npx nuxi@latest module add pinia 的 Pinia 模块或遵循 module's installation steps
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
    }
  }
})

高级用法

¥Advanced Usage

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.

共享状态

¥Shared State

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

¥By using auto-imported composables we can define global type-safe states and import them across the app.

composables/states.ts
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() // Same as useState('color')
</script>

<template>
  <p>Current color: {{ color }}</p>
</template>

使用第三方库

¥Using third-party libraries

Nuxt 过去依赖 Vuex 库来提供全局状态管理。如果你要从 Nuxt 2 迁移,请前往 迁移指南

¥Nuxt used to rely on the Vuex library to provide global state management. If you are migrating from Nuxt 2, please head to the migration guide.

Nuxt 对状态管理没有有态度,因此你可以根据自己的需求选择合适的解决方案。与最流行的状态管理库集成,包括:

¥Nuxt is not opinionated about state management, so feel free to choose the right solution for your needs. There are multiple integrations with the most popular state management libraries, including:

  • Pinia - Vue 官方建议
  • Harlem - 不可变的全局状态管理
  • XState - 使用状态机方法,并附带用于可视化和测试状态逻辑的工具