Created
November 21, 2024 17:49
-
-
Save lorens-osman-dev/13921b96ec95b12c602fce0328a8220e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createPinia, defineStore } from "pinia"; | |
import { ref, type Ref, type UnwrapRef } from "vue"; | |
const pinia = createPinia(); | |
export const newStore = <T>(storeName: string, value: T) => { | |
const start = defineStore(storeName, () => { | |
const state = ref(value); | |
function update(newValue: UnwrapRef<T>) { | |
state.value = newValue; | |
} | |
return { state, update }; | |
}); | |
const store = start(pinia); | |
return store; | |
}; | |
class GlobalStore<G> { | |
stores: { [key: string]: ReturnType<typeof newStore<G>> } = {}; | |
storeNames: string[] = []; | |
set(storeName: string, value: G): void { | |
if (!this.stores[storeName]) { | |
this.stores[storeName] = newStore<G>(storeName, value); | |
this.storeNames.push(storeName); | |
} | |
} | |
} | |
const globalStore = new GlobalStore(); | |
export default globalStore; | |
const _ = new GlobalStore(); | |
//usage | |
_.set("bigStore", 45); | |
_.set("nameStore", "lorens"); | |
console.log(_.stores.bigStore.state); //45 | |
console.log(_.stores.nameStore.state); //lorens | |
_.stores.bigStore.update(88); | |
_.stores.nameStore.update("ahmed"); | |
console.log(_.stores.bigStore.state); //88 | |
console.log(_.stores.nameStore.state); //ahmed |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment