1.1.1 • Published 3 years ago
vue-global-store v1.1.1
vue-global-store
Install
npm install --save vue-global-store
Usage
vue-global-store for Vue3
// store.js
import { createGlobal } from "vue-global-store";
const store = createGlobal({
state: {
name: "jack",
age: 18,
},
behavior: {
SET_NAME(state, value) {
state.name = value;
},
SET_AGE(state, value) {
state.age = value;
},
},
});
export default store;
// main.js
import { createApp } from "vue";
import App from "./App.vue";
import Store from "@/store";
app.use(Store)
app.mount("#app");
//index.vue
<script>
import { computed } from "vue";
import { useGlobal } from "vue-global-store";
export default {
setup() {
const store = useGlobal();
return {
name: computed(() => store.state.name), // jack
age: computed(() => store.state.age), // 18
clickHandle: () => {
store.commit("SET_AGE", 20) // age = 20
}
}
}
}
<script>
You can also add the name attribute
// store.js
const store = createGlobal({
name: "user",
state: {},
behavior: {},
});
// index.vue
import { useGlobal } from "@/store";
const store = useGlobal("user");
...
In the typescript
// store.ts
import { createGlobal, useGlobal as useBaseGlobal, GlobalState, InjectionKey } from "vue-global-store";
// InjectionKey You can do that
// import { InjectionKey } from "vue";
interface State {
name: string;
age: number;
}
export const InjectKey: InjectionKey<GlobalState<State>> = Symbol();
const store = createGlobal<State>({
state: {},
behavior: {},
});
export const useGlobal = () => {
return useBaseGlobal(InjectKey);
};
export default store;
// main.ts
import { createApp } from "vue";
import App from "./App.vue";
import Store, { InjectKey } from "@/store";
app.use(Store, InjectKey)
app.mount("#app");
// index.vue
import { useGlobal } from "@/store";
const store = useGlobal();
...
License
The MIT License (MIT). Please see License File for more information.