[Vuejs]-Vuex โ€“ Do not mutate vuex store state outside mutation handlers with getters

0๐Ÿ‘

โœ…

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>

Leave a comment