狀態管理
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/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>
在 文件 > 4 X > 示例 > 特性 > 狀態管理 中閱讀和編輯即時示例。
要全域性使快取狀態失效,請參閱
clearNuxtState
工具函式。初始化狀態
大多數情況下,您會希望使用非同步解析的資料來初始化狀態。您可以使用 app.vue
元件和 callOnce
工具函式來完成此操作。
app/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
動作,它允許在渲染頁面之前在伺服器端填充儲存的初始狀態。與 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
},
},
})
<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>
在 文件 > 4 X > 示例 > 高階 > 區域設定 中閱讀和編輯即時示例。
共享狀態
透過使用 自動匯入的可組合函式,我們可以定義全域性型別安全狀態並在整個應用程式中匯入它們。
composables/states.ts
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() // Same as useState('color')
</script>
<template>
<p>Current color: {{ color }}</p>
</template>
使用第三方庫
Nuxt 過去依賴 Vuex 庫來提供全域性狀態管理。如果您正在從 Nuxt 2 遷移,請前往 遷移指南。
Nuxt 在狀態管理方面沒有特定偏好,因此您可以根據自己的需求自由選擇合適的解決方案。有多種與最流行的狀態管理庫的整合,包括