状态管理
Nuxt 提供强大的状态管理库和 useState 组合函数,创建一个响应式且友好的 SSR 共享状态。
Nuxt 提供了 useState
组合函数,用于在组件之间创建一个响应式且友好的 SSR 共享状态。
useState
是一个支持 SSR 的 ref
替代品。其值将在服务器端渲染后(在客户端水合期间)被保留,并通过一个唯一的键在所有组件之间共享。
因为
useState
内的数据将被序列化为 JSON,因此重要的是,它不应包含任何无法序列化的内容,例如类、函数或符号。最佳实践
永远不要在
例如,执行
<script setup>
或 setup()
函数外部定义 const state = ref()
。例如,执行
export myState = ref({})
将导致状态在服务器上的请求之间共享,并可能导致内存泄漏。相反,可以使用
const useX = () => useState('x')
示例
基本用法
在这个示例中,我们使用组件本地的计数器状态。任何使用 useState('counter')
的其他组件都会共享相同的响应式状态。
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>
Read and edit a live example in Docs > Examples > Features > State Management.
要全局使缓存状态失效,请参见
clearNuxtState
工具。初始化状态
大多数情况下,您将希望使用异步解析的数据初始化您的状态。您可以使用 app.vue
组件和 callOnce
工具来实现。
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
动作,允许在渲染页面之前服务器端填充 store 的初始状态。与 Pinia 的结合使用
在这个示例中,我们利用 Pinia 模块 创建一个全局 store,并在应用程序中使用它。
确保通过
npx nuxi@latest 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
}
}
})
<script setup lang="ts">
const website = useWebsiteStore()
await callOnce(website.fetch)
</script>
<template>
<main>
<h1>{{ website.name }}</h1>
<p>{{ website.description }}</p>
</main>
</template>
高级用法
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)))
}
<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="locale of locales" :key="locale" :value="locale">
{{ locale }}
</option>
</select>
</div>
</template>
Read and edit a live example in Docs > Examples > Advanced > Locale.
共享状态
通过使用 自动导入的组合函数,我们可以定义全局的类型安全状态,并在应用程序中导入它们。
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() // 同上 useState('color')
</script>
<template>
<p>当前颜色: {{ color }}</p>
</template>
使用第三方库
Nuxt 曾经依赖 Vuex 库来提供全局状态管理。如果您正从 Nuxt 2 迁移,请访问 迁移指南。
Nuxt 对状态管理没有固定意见,因此请自由选择适合您需求的解决方案。与最流行的状态管理库有多个集成,包括: