【问题标题】:Vuex - Do not mutate vuex store state outside mutation handlers with gettersVuex - 不要在突变处理程序之外用 getter 改变 vuex 存储状态
【发布时间】:2020-05-15 17:40:22
【问题描述】:

/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'}],
})

当我尝试运行我的 /pages/index.vue 时,我无法保留数组的第一个元素。 我有这个错误:[vuex] Do not mutate vuex store state outside mutation handlers.

【问题讨论】:

  • splice 改变它所操作的数组。这就是您收到此错误的原因。尝试使用slice 或不会改变原始数组的方法。

标签: vue.js vuex


【解决方案1】:

如果你想改变你的状态,你必须使用突变。

如果只想获取第一个元素,可以使用扩展运算符或方法切片。

请看下面的例子:

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>

【讨论】:

    猜你喜欢
    • 2019-09-24
    • 2018-02-13
    • 2022-01-09
    • 1970-01-01
    • 2020-03-30
    • 2023-03-09
    • 2016-11-16
    • 1970-01-01
    • 2019-11-30
    相关资源
    最近更新 更多