2👍
✅
Sharing the same variable is usually called "store" (see Pinia for example)
https://pinia.vuejs.org/
// store.ts
let store; // global value used by the whole application
export function useStore() {
return store ??= reactive({
foo: 'bar',
get length(){ return this.foo.length },
bar(){ console.log(this.foo) }
})
}
// file.vue
import {useStore} from 'store.ts'
const store = useStore()
<template>
{{ store.foo }}
</template>
It will be exactly same object in all the component tree.
Say, you have a tic-tac-toe game, with cell values using the store.
If you will have multiple grids, they will have the same game state, because their state is shared in the same store
Provide/Inject allows you to make that store local to one component and its children only
// store.ts
export function provideStore() {
const store = reactive({
foo: 'bar',
get length(){ return this.foo.length },
bar(){ console.log(this.foo) }
})
provide('my-store', store)
return store;
}
export function useStore() {
return inject('my-store')
}
// file.vue
import {provideStore} from 'store.ts'
const store = provideStore()
<template>
{{ store.foo }}
<Child />
</template>
// child.vue
import {useStore} from 'store.ts'
const store = useStore()
<template>
{{ store.foo }}
</template>
Source:stackexchange.com