nuxt3中的狀態(tài)管理
Nuxt3提供useState組合式函數(shù),使用此函數(shù)可以創(chuàng)建一個(gè)可在整個(gè)組件中共享的狀態(tài),此狀態(tài)還是響應(yīng)式的并且對于SSR非常友好。
之所以是SSR友好的,是因?yàn)槿绾卧诜?wù)端使用useState保存狀態(tài)的話,此狀態(tài)會在服務(wù)端渲染后序列化并發(fā)送到客戶端,這樣共享狀態(tài)可以在客戶端的所有組件中使用。
::: alertinfo
注意,useState只能在setup和lifecycle Hooks中使用。
:::
::: alertwarning
由于在useState中的數(shù)據(jù)會被序列化成JSON, 所以你設(shè)置的狀態(tài)對象中最好不要包含無法被序列化的數(shù)據(jù),例如 類,方法或者符號
:::
::: alertdanger
在<script setup>或者setup()之外,先別不要定義const state = ref()。這種狀態(tài)被所有的訪問你網(wǎng)站的用戶共享,這樣會導(dǎo)致內(nèi)存泄露。
:::
::: alertsuccess
取而代之的是使用 const useX = () => useState('x')。
:::
示例
基礎(chǔ)使用方式
<!-- app.vue -->
<script setup>
const counter = useState('counter', () => Math.round(Math.random() * 1000))
</script>
<template>
<div>
Counter: {{ counter }}
<button @click="counter++">
+
</button>
<button @click="counter--">
-
</button>
</div>
</template>
共享狀態(tài)
使用auto-imported commposables 我們可以定義一個(gè)全局的,類型安全的狀態(tài)。
// composeables/states.ts
export const useCounter = () => useState<number>('counter', () => 0)
export const useColor = () => useState<string>('color', () => 'pink')
<!-- app.vue -->
<script setup>
const color = useColor() // Same as useState('color')
</script>
<template>
<p>Current color: {{ color }}</p>
</template>
這樣在項(xiàng)目中使用這些狀態(tài)就更加方便了。
版權(quán)聲明:本文為凸然網(wǎng)站的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請附上原文出處鏈接及本聲明。
原文鏈接:nuxt3中的狀態(tài)管理