javascriptvue.jsvuejs3pinia

Generating Pinia stores like class objects


In my code I need 5 identical Pinia stores with the same fields and methods. But each store has specific data. How can I create a "Class" that generates Pinia stores from a template?

import { ref } from 'vue'
import { defineStore } from 'pinia'

class StoreGenerator {
    constructor(store_name) {
        export const TeamStore = defineStore(store_name, () => {
            const objects = ref([])

            function add_object(info) {
                objects.value.push(info)
            }

            return { objects, add_object }
        })
    }
}

Solution

  • There's a problem with syntax, export keyword is allowed at top level.

    There is no need for a class because the existence of class instance is not justified. It can be factory function:

    export const createMyStore = name => defineStore(name, () => { ... });
    

    Then it can be used in store module:

    export const myFooStore = createMyStore('foo');
    

    Pinia stores are convenient to use in modular way, but depending on the case, they could be merged into one store that handles several types of data:

    export const myStore = defineStore('myStore', () => {
        const objects = ref({ foo: [], ... )
    
        function add_object(type info) {
            objects.value[type].push(info)
        }
    
        return { objects, add_object }
    })