Alete
Alete

Reputation: 49

Mutations undefined Vuex

I have an issue with mutations in Vuex - In my component I have passed the getters and mutations, so that I can used the data. However, the getters are getting passed down just fine and can be retrieved from the component, but regarding the mutations, they all seem to be getting undefined. I have another component with identical setup, which seems to work fine.

Here is the code related to the component I have an issue with: https://codesandbox.io/s/nlpvz0y6m

So far, I have tried retrieving the data by importing the whole store but it isn't what I must do and not optimal.

Please advise further.

store:

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export const store = new Vuex.Store({
  state: {
    stats: {
      controls: {
        spin: false
      }
    },
    getters: {
      isSpinning: state => {
        return state.controls.spin;
      }
    },
    mutations: {
      spinIt(state) {
        return (state.controls.spin = !state.controls.spin);
      }
    }
  }
});

component:

<template>
    <div>
        <div class="spin">
            <span @click="spinIt">SPIN</span>
        </div>
    </div>
</template>

<script>
  import {mapMutations} from 'vuex';
  import {mapGetters} from 'vuex';

  export default {
    name: 'Stake',
    computed: {
      ...mapMutations(['spinIt']),
      ...mapGetters(['isSpinning'])
    }
  }

</script>

Upvotes: 3

Views: 1911

Answers (1)

Peter Kota
Peter Kota

Reputation: 8340

First you need restructure the Vuex instance by the following:

export const store = new Vuex.Store({
  state: {
    stats: {
      controls: {
        spin: false
      }
    },
  },
  getters: {
    isSpinning: state => {
      return state.stats.controls.spin;
    }
  },
  mutations: {
    spinIt(state) {
      return (state.stats.controls.spin = !state.stats.controls.spin);
    }
  }
});

Now you will access the getters and mutations.

After that, move the mapMutations into the methods block in your Spin.vue:

<script>
  import {mapMutations} from 'vuex';
  import {mapGetters} from 'vuex';

  export default {
    name: 'Stake',
    computed: {
      ...mapGetters(['isSpinning'])
    },
    methods: {
      ...mapMutations(['spinIt'])
    }
  }

</script>

Upvotes: 2

Related Questions