useState 可组合函数,用于创建响应式且兼容 SSR 的共享状态。Nuxt 提供了 useState 可组合函数,用于在组件之间创建响应式且兼容 SSR 的共享状态。
useState 是一个兼容 SSR 的替代品。其值在服务器端渲染后(在客户端水合期间)将保留,并通过唯一键在所有使用该键的组件之间共享。ref
useState 中的数据将被序列化为 JSON,因此其中不能包含任何无法序列化的内容,例如类、函数或 Symbol。<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: {{ counter }}
<button @click="counter++">
+
</button>
<button @click="counter--">
-
</button>
</div>
</template>
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>
nuxtServerInit 动作,它允许在页面渲染之前在服务器端填充存储的初始状态。在此示例中,我们利用 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
},
},
})
<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 birthday</h1>
<p>{{ date }}</p>
<label for="locale-chooser">Preview a different locale</label>
<select
id="locale-chooser"
v-model="locale"
>
<option
v-for="loc of locales"
:key="loc"
:value="loc"
>
{{ loc }}
</option>
</select>
</div>
</template>
通过使用 自动导入的可组合函数,我们可以定义全局类型安全的状态并在整个应用程序中导入它们。
export const useColor = () => useState<string>('color', () => 'pink')
<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>
Nuxt 过去依赖 Vuex 库来提供全局状态管理。如果您正在从 Nuxt 2 迁移,请前往 迁移指南。
Nuxt 不对状态管理持特定观点,因此您可以随意选择适合您需求的解决方案。目前有多种与最流行的状态管理库的集成,包括