Nuxt内置了组合式API: useState
,可以用来管理全局状态并支持在服务端使用。
示例:
<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>
在下面这个例子中,我们使用使用组合式API检测浏览器默认语言,并存储在useState
定义的变量中。
官方示例:https://nuxt.com/docs/examples/other/locale
利用Nuxt自动导入组合式API,可以更便捷地使用useState
composables/state.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>
useState
在状态管理方面并不专业。你可以根据自己的需要,选择流行的第三方库: