Sharing Global State with TanStack Store in Vue
Showcase how to configure TanStack Store as a global state management solution in a Vue application, focusing on creating a shared store and accessing it within multiple Vue components using the composition API.
import { createStore } from '@tanstack/vue-store';
export const useCounterStore = createStore({
id: 'counter',
state: () => ({ count: 0 }),
actions: {
increment() {
this.state.count++;
},
decrement() {
this.state.count--;
}
}
});
This code snippet creates a global store using TanStack Store for Vue. It defines a store named 'counter' with a piece of state 'count' and two actions: 'increment' and 'decrement' to modify the state.
import { createApp } from 'vue';
import App from './App.vue';
import { useCounterStore } from './store/counter';
const app = createApp(App);
app.provide('counterStore', useCounterStore());
app.mount('#app');
This snippet showcases how to provide the created 'counterStore' globally to the Vue app. The 'provide' method is used to inject the store, making it accessible in any component within the application.
import { inject } from 'vue';
export default {
setup() {
const counterStore = inject('counterStore');
return {
count: counterStore.state.count,
increment: counterStore.actions.increment,
decrement: counterStore.actions.decrement
};
}
};
In this part, we demonstrate how to access the 'counterStore' in a Vue component using the 'inject' function within the 'setup' method of the Composition API. It allows the component to read the store's state and execute its actions.