Home > Software engineering >  Confused about Vuex modules
Confused about Vuex modules

Time:11-29

I'll try and lay this out as cleanly as possible:

I have a Vue component that I'm rendering called World.vue:

<template>
  <v-container>
    This is the whole world
    <v-btn @click="test()" />
  </v-container>
</template>

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

export default {
  computed: {
    ...mapState('drawers', ['isEquipmentOpen']),
  },
  methods: {
    ...mapActions('drawers', ['test']),
  },
};
</script>

And I have a module in for the Vuex store called drawers (drawers.js):

export default {
  namespaced: true,
  state: {
    isEquipmentOpen: false,
  },
  actions: {
    test(state) {
      console.log(state.isEquipmentOpen);
      state.isEquipmentOpen = !state.isEquipmentOpen;
    },
  },
};

What I don't understand is why when test() is called, it can't access isEquipmentOpen (logs a value of undefined). How can I manipulate isEquipmentOpen?

CodePudding user response:

You cannot mutate state values from actions.

  • You'll need to create a mutations property, create a setter method in it and call it in order to change the value.
  • Pass a { commit } parameter to method in actions property.

You don't need to pass the state parameter in actions methods. Make sure that the string value in the commit() is the same as the setter name.

export default {
  namespaced: true,
  state: {
    isEquipmentOpen: false,
  },
  actions: {
    test({ commit }) {
      console.log(state.isEquipmentOpen);
      
      commit("setIsEquipmentOpen");
    },
  mutations: {
    setIsEquipmentOpen: state => state.isEquipmentOpen != state.isEquipmentOpen 
  },
};

Hope you understood the answer!

  • Related