Skip to content
Alexander Opalic
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) => anyuseStore = (id: stringid: string) => defineStore(`store-${id: stringid}`, () => {
  const const data: anydata = ref({})
  
  return { data: anydata }
})()

// Usage example:
const const tableOneStore: anytableOneStore = const useStore: (id: string) => anyuseStore('table1')
const const tableTwoStore: anytableTwoStore = const useStore: (id: string) => anyuseStore('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