Alexander Opalic
Dynamic Pinia Stores in Vue 3
Create dynamic Pinia stores with unique IDs for multiple component instances
Today I learned how to create dynamic Pinia stores in Vue 3 by generating unique store IDs. This is super useful when you need separate state management for multiple instances of the same component, like data tables or forms.
Here’s how to do it:
const const useStore: (id: string) => any
useStore = (id: string
id: string) => defineStore(`store-${id: string
id}`, () => {
const const data: any
data = ref({})
return { data: any
data }
})()
// Usage example:
const const tableOneStore: any
tableOneStore = const useStore: (id: string) => any
useStore('table1')
const const tableTwoStore: any
tableTwoStore = const useStore: (id: string) => any
useStore('table2')
Each store instance gets its own isolated state, making it perfect for managing multiple independent components. This approach prevents state conflicts and keeps your data properly organized.
Key benefits:
- Isolated state per component instance
- Clean and maintainable code
- Type-safe with TypeScript
- Perfect for dynamic components
#VueJS
#vue
#pinia
#typescript