Search code examples
vue.jsvuex

Vuex - Do not mutate vuex store state outside mutation handlers with getters


/pages/index.vue

computed: {
    escapeValues() { return this.$store.state.escapeOnline.splice(0, 1); }
}

/store/index.js

export const state = () => ({
  escapeOnline: [{id: 1, name: 'titi'}, {id: 2, 'toto'}],
})

When I try to run my /pages/index.vue, I can't keep the first element of my array. And I have this error : [vuex] Do not mutate vuex store state outside mutation handlers.


Solution

  • If you want to change your state you must to use a mutation.

    If you want only get first element, you can use spread operator or the method slice.

    See the following example:

    import Vue from 'vue';
    import Vuex from 'vuex';
    
    Vue.use(Vuex);
    
    export default new Vuex.Store({
      state: {
        escapeOnline: [{ id: '1' }, { id: '2' }, { id: '3' }, { id: '4' }, { id: '5' }, { id: '6' }],
      },
      mutations: {
        removeFirst(state) {
          state.escapeOnline.splice(0, 1);
        },
      },
    });
    
    <template>
      <div id="app">
        <div>
          {{ $store.state.escapeOnline }}
        </div>
        <div>
          <button @click="showFirst">Show First in console.log</button>
          <button @click="removeFirst">Remove First</button>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      name: 'App',
      methods: {
        removeFirst() {
          this.$store.commit('removeFirst');
        },
        showFirst() {
          let [first] = this.$store.state.escapeOnline;
          console.log(first);
        },
      },
    };
    </script>