跳到主要内容

createGlobalState

分类
导出大小
152 B
上次更改
3 个月前
相关

在全局范围内保持状态,以便在 Vue 实例之间重用。

演示

name: Banana
color: Yellow
size: Medium

用法

无持久化 (存储在内存中)

ts
// store.ts
import { 
createGlobalState
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
export const
useGlobalState
=
createGlobalState
(
() => { const
count
=
shallowRef
(0)
return {
count
}
} )

一个更大的示例

ts
// store.ts
import { 
createGlobalState
} from '@vueuse/core'
import {
computed
,
shallowRef
} from 'vue'
export const
useGlobalState
=
createGlobalState
(
() => { // state const
count
=
shallowRef
(0)
// getters const
doubleCount
=
computed
(() =>
count
.
value
* 2)
// actions function
increment
() {
count
.
value
++
} return {
count
,
doubleCount
,
increment
}
} )

带持久化

使用 useStorage 存储在 localStorage

ts
// store.ts
import { 
createGlobalState
,
useStorage
} from '@vueuse/core'
export const
useGlobalState
=
createGlobalState
(
() =>
useStorage
('vueuse-local-storage', 'initialValue'),
)
ts
// component.ts
import { 
useGlobalState
} from './store'
export default
defineComponent
({
setup
() {
const
state
=
useGlobalState
()
return {
state
}
}, })

类型声明

ts
export type 
CreateGlobalStateReturn
<
Fn
extends
AnyFn
=
AnyFn
> =
Fn
/** * Keep states in the global scope to be reusable across Vue instances. * * @see https://vueuse.org.cn/createGlobalState * @param stateFactory A factory function to create the state * * @__NO_SIDE_EFFECTS__ */ export declare function
createGlobalState
<
Fn
extends
AnyFn
>(
stateFactory
:
Fn
,
):
CreateGlobalStateReturn
<
Fn
>

来源

源代码演示文档

贡献者

Anthony Fu
SerKo
Robin
Anthony Fu
IlyaL
童欧巴
JD Solanki
Ducz01
Tobi
thefeymesaleng
plylrnsdy
wheat
Preston Alvarado
jelf

更新日志

v13.6.0
d32f8 - refactor: 为所有纯函数添加 @__NO_SIDE_EFFECTS__ 注释 (#4907)
v13.1.0
c1d6e - feat(shared): 确保返回类型存在 (#4659)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)

根据 MIT 许可证发布。