nuxt3中的状态管理

nuxt3中的状态管理

Nuxt3提供useState组合式函数,使用此函数可以创建一个可在整个组件中共享的状态,此状态还是响应式的并且对于SSR非常友好。
之所以是SSR友好的,是因为如何在服务端使用useState保存状态的话,此状态会在服务端渲染后序列化并发送到客户端,这样共享状态可以在客户端的所有组件中使用。

::: alertinfo
注意,useState只能在setuplifecycle Hooks中使用。
:::

::: alertwarning
由于在useState中的数据会被序列化成JSON, 所以你设置的状态对象中最好不要包含无法被序列化的数据,例如 类,方法或者符号
:::



::: alertdanger
<script setup>或者setup()之外,先别不要定义const state = ref()。这种状态被所有的访问你网站的用户共享,这样会导致内存泄露。
:::



::: alertsuccess
取而代之的是使用 const useX = () => useState('x')
:::

示例

基础使用方式

<!-- 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>

共享状态

使用auto-imported commposables 我们可以定义一个全局的,类型安全的状态。

// 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>

这样在项目中使用这些状态就更加方便了。




版权声明:本文为凸然网站的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:nuxt3中的状态管理

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容