how to create dynamic store vue 3
- User
how to create dynamic store vue 3
- Assistant
Creating a dynamic store in Vue 3 typically involves using a state management solution like Vuex or Pinia, or setting up a custom reactive system using Vue's Composition API. Below, I'll provide an example using both the Composition API and Pinia, which is the recommended state management library for Vue 3 moving forward.
Using the Composition API
If your state management needs are simple, you can use Vue's built-in reactivity system.
-
Create a reactive state using
reactiveorref:javascript// store.js import { reactive, computed } from 'vue'; const state = reactive({ count: 0, }); const getters = { doubleCount: computed(() => state.count * 2), }; const actions = { increment() { state.count++; }, decrement() { state.count--; }, }; export default { state, getters, ...actions, }; -
Use it in your component:
vue<!-- MyComponent.vue --> <template> <div> <p>Count: {{ store.state.count }}</p> <p>Double Count: {{ store.getters.doubleCount }}</p> <button @click="store.increment">Increment</button> <button @click="store.decrement">Decrement</button> </div> </template> <script> import { defineComponent } from 'vue'; import store from './store'; export default defineComponent({ setup() { return { store }; }, }); </script>
Using Pinia
Pinia is a modern state management library for Vue that integrates seamlessly and offers a more intuitive API than Vuex.
-
Install Pinia:
Run the following command to install Pinia:
bashnpm install pinia -
Set up a Pinia store:
javascript// stores/counter.js import { defineStore } from 'pinia'; export const useCounterStore = defineStore('counter', { state: () => ({ count: 0, }), getters: { doubleCount: (state) => state.count * 2, }, actions: { increment() { this.count++; }, decrement() { this.count--; }, }, }); -
Use the store in your component:
vue<!-- MyComponent.vue --> <template> <div> <p>Count: {{ counter.count }}</p> <p>Double Count: {{ counter.doubleCount }}</p> <button @click="counter.increment">Increment</button> <button @click="counter.decrement">Decrement</button> </div> </template> <script> import { defineComponent } from 'vue'; import { useCounterStore } from './stores/counter'; export default defineComponent({ setup() { const counter = useCounterStore(); return { counter }; }, }); </script> -
Setup Pinia in your main file:
Ensure that you set up Pinia in your
main.jsormain.tsfile:javascript// main.js import { createApp } from 'vue'; import { createPinia } from 'pinia'; import App from './App.vue'; const app = createApp(App); app.use(createPinia()); app.mount('#app');
Pinia is typically preferred for new Vue 3 projects because of its simplicity and powerful features like hot module replacement, type safety, and better integration options. However, for small-scale state management needs, Vue's built-in reactivity system can be sufficient.
-