Skip to content

createGlobalState

类别
导出体积
152 B
上次更改
2 months ago
相关

将状态保留在全局范围内,以便在 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
(
() => { // 状态 const
count
=
shallowRef
(0)
// 计算属性 const
doubleCount
=
computed
(() =>
count
.
value
* 2)
// 动作 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
/** * 在全局范围内保留状态,以便在 Vue 实例之间重复使用。 * * @see https://vueuse.org/createGlobalState * @param stateFactory 用于创建状态的工厂函数 * * @__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

更新日志

d32f8 - refactor: add @__NO_SIDE_EFFECTS__ annotations to all pure functions (#4907)
c1d6e - feat(shared): ensure return types exists (#4659)
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)