【问题标题】:How can I update state in vuex ? vue.js 2如何更新 vuex 中的状态? Vue.js 2
【发布时间】:2017-09-06 09:34:53
【问题描述】:

我的 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 警告]:观察者回调错误“function () { return this._data.$$state }":(在 中找到)

错误:[vuex] 不要在突变之外改变 vuex 存储状态 处理程序。

我该如何解决?

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

【问题讨论】:

    标签: vue.js vuejs2 vue-component vuex


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您一定是因为在您的 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 才能使用扩展运算符:...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-16
        • 2021-06-07
        • 2021-06-19
        • 1970-01-01
        • 2017-05-20
        • 2021-07-21
        • 2019-10-15
        相关资源
        最近更新 更多