Skip to content

createGlobalState

Category
Export Size
152 B
Last Changed
4 days ago
Related

Keep states in the global scope to be reusable across Vue instances.

Demo

name: Banana
color: Yellow
size: Medium

Usage

Without Persistence (Store in Memory)

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

A bigger example:

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
}
} )

With Persistence

Store in localStorage with useStorage:

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
}
}, })

Type Declarations

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/createGlobalState * @param stateFactory A factory function to create the state * * @__NO_SIDE_EFFECTS__ */ export declare function
createGlobalState
<
Fn
extends
AnyFn
>(
stateFactory
:
Fn
,
):
CreateGlobalStateReturn
<
Fn
>

Source

SourceDemoDocs

Contributors

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

Changelog

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

Released under the MIT License.

Build faster with AI
New Masterclass to help you leverage AI in your Vue workflow
Get Early Access