nuxt3中的狀態(tài)管理

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只能在setuplifecycle 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)管理

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容