State

Nuxt 提供可组合的 useState 来创建跨组件的并且对 SSR 友好的响应式状态。

useState 是一个 SSR 友好的 ref 替代品。它的值将会在服务端渲染(客户端渲染期间)后保留,并且使用唯一的键在所有组件之间共享。

签名

  1. useState<T>(key: string, init?: () => T): Ref<T>
  • key :唯一的键确保数据请求能够正确并且不被重复

  • init :在 state 还未初始化时提供初始值的函数

  • T :(仅用作于 typescript )描述 state 的类型

:::info 👉 useState 仅在 setup生命周期钩子 中生效。


:::

最佳实践

:::danger 🚨 请不要在<script setup>setup() 函数以外定义 const state = ref()
这种 state 将被所有访问您网站的用户共享,并可能导致内存泄漏! :::

:::tip ✅ 而是使用 const useX = () ⇒ useState('x')
:::

例子

基本用法

在这个例子中,我们使用一个组件内部的 counter 状态,任何其他使用 useState('counter') 的组件都将共享同一个响应式状态。

  1. <script setup>
  2. const counter = useState('counter', () => Math.round(Math.random() * 1000))
  3. </script>
  4. <template>
  5. <div>
  6. Counter: {{ counter }}
  7. <button @click="counter++">
  8. +
  9. </button>
  10. <button @click="counter--">
  11. -
  12. </button>
  13. </div>
  14. </template>

在 StackBlitz 中打开

高级用法

在这个例子中,我们使用一个 composables 从 HTTP 请求头中获取用户默认的环境保存然后在一个名为 local 的状态中。

在 StackBlitz 中打开

共享状态

通过使用自动导入 composables,我们可以定义全局的安全类型状态并且在整个应用中导入。

  1. // composables/states.ts
  2. export const useCounter = () => useState<number>('counter', () => 0)
  3. export const useColor = () => useState<string>('color', () => 'pink')
  1. <script setup>
  2. const color = useColor() // Same as useState('color')
  3. </script>
  4. <template>
  5. <p>Current color: {{ color }}</p>
  6. </template>