如何在 vuex 中更新状态? vue.js 2

How can I update state in vuex ? vue.js 2

我的 vue 组件是这样的:

<template>
    <div>
        <div class="row">
            <div class="col-sm-3">
                <div class="form-group">
                    <label for="status" class="sr-only">Status</label>
                    <select class="form-control" v-model="selected" @change="filterByStatus()">
                        <option value="">All Status</option>
                        <option v-for="status in orderStatus" v-bind:value="status.id">{{ status.name }}</option>
                    </select>
                </div>
            </div>
        </div>
        ...
    </div>
</template>

<script>
    import { mapActions, mapGetters } from 'vuex';
    export default {
        ...
        data() {
            return { selected: '' }
        },
        methods: {
            filterByStatus: function() {
                this.$store.state.status = this.selected
            }
        }
    }
</script>

我的模块顺序 vuex 是这样的:

import { set } from 'vue'
import order from '../../api/order'
import * as types from '../mutation-types'

const state = {
    status: ''
}
const getters = {
    ...
}
const actions = {
    ...
}

const mutations = {
    ...
}

export default {
    state,
    getters,
    actions,
    mutations
}

我使用这个:this.$store.state.order.status = this.selected,在执行时更新状态,但是存在这样的错误:

[Vue warn]: Error in callback for watcher "function () { return this._data.$$state }": (found in )

Error: [vuex] Do not mutate vuex store state outside mutation handlers.

我该如何解决?

我想要更新状态,因为我想要另一个组件使用的值

您一定是因为在 vuex 商店设置中启用 strict mode 而收到此错误。

不过,这是一个很好的做法。除非在突变中,否则不得修改状态。

所以要使用新设置的商店;有一个突变:

const mutations = {
   mutateOrderStatus: function (state, payload) {
      state.order.status = payload
   }
}

const actions = {
   updateOrderStatusAction: function ({commit}, payload) {
      commit('mutateOrderStatus', payload)
   }
}

现在将其包含在您的组件中,例如:

...
methods: {
  ...mapActions([ // spread operator so that other methods can still be added.
    'updateOrderStatusAction'
  ]),
  filterByStatus: function() {
    this.updateOrderStatusAction(this.selected)
  }
}

注意:您可能需要安装 babelbabel-preset-es2015 才能使用传播运算符:....

我刚刚找到了那个问题的解决方案,我用过 Vue.set(state.element, elementIndex, newElement);