状态管理
Nuxt 提供强大的状态管理库和 useState 可组合函数以创建响应式且为 SSR 友好的共享状态。
Geprüfte Übersetzung ·0 % geprüft
Nuxt 提供 useState 可组合函数,用于创建响应式且对 SSR 友好的状态,并在多个组件之间共享。
useState 是对 SSR 友好的 ref 替代方案。它的值会在服务器端渲染后(客户端 hydration 期间)保留,并通过唯一键在所有使用它的组件之间共享。
由于
useState 中的数据会被序列化为 JSON,因此请确保其中不包含无法序列化的内容,例如类、函数或符号。最佳实践
切勿在
例如,执行
<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,它允许在服务器端渲染页面之前填充 store 的初始状态。与 Pinia 一起使用
在此示例中,我们利用 Pinia 模块 创建一个全局 store 并在应用中使用它。
请确保使用
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
},
},
})<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="loc of locales"
:key="loc"
:value="loc"
>
{{ loc }}
</option>
</select>
</div>
</template> Read and edit a live example in Docs > Examples > Advanced > Locale.
共享状态
通过使用自动导入的可组合函数,我们可以定义全局类型安全状态,并在整个应用中导入这些状态。
export const useColor = () => useState<string>('color', () => 'pink')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>使用第三方库
Nuxt 曾依赖 Vuex 库来提供全局状态管理。如果你正在从 Nuxt 2 迁移,请参阅迁移指南。
Nuxt 对状态管理并不强制使用特定方案,因此请根据您的需求自由选择合适的解决方案。下面是与一些流行状态管理库的集成:
Was this helpful?