humptydumpty
humptydumpty

Reputation: 143

Multiple instances of a vuex module still share the same state?

According to the docs, if I simply return the state as a function, I should be able to reuse the store module. However, when I did this, my vuex store module still shared state across all the component instances.

Here's the component markup:

<template>
    <button class="button" type="button" @click="onClick">{{ count }}</button>
</template>

<script>
    import {mapState, mapMutations} from 'vuex';

    export default {
        name: 'sub-component',
        computed: {
            ...mapState('myModule', ['count'])
        },
        methods: {
            ...mapMutations('myModule', ['INCREMENT_COUNT']),

            onClick() {
                this.INCREMENT_COUNT();
            }
        }
    };
</script>

Here's my store module:

const namespaced = true;

const state = () => {
    return {
        count: 0
    };
};

const mutations = {
    INCREMENT_COUNT(state) {
        state.count++;
    },
};

export default {
    namespaced,
    state,
    mutations
};

So, in my parent component, I have an arbitrary number of "sub-component" (button) instances. When I click, it does increment, but it increments for all of the instances. Is there a way to still utilize Vuex store without sharing the state across all the instances of my sub-component?

Context: I'm using Vuex in a SPA -- so a standard use-case for managing the state/methods across components in SPA. But I also have deeply nested components that interact and update other components in the SPA (but these other components need to maintain to their own state). Yes, I don't have to use Vuex, but it seemed like it would be cleaner.

Upvotes: 1

Views: 788

Answers (0)

Related Questions