How to update state in vuex? vue.js 2

My vue component looks like this:

<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>

      

My vuex module order is like this:

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
}

      

I use this: this.$store.state.order.status = this.selected

to update the state when it runs, but there are errors like this:

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

Error: [vuex] Don't mutate vuex store state outside of mutation handlers.

How can I solve it?

I want the update state because I want the value used by a component of another

+3


source to share


1 answer


You should be getting this error due to enabling strict mode in your vuex store setup.

This is good practice, however. You must not change state except from mutation.

So, to use the new settings store; have a mutation like:

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

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

      



Now include it in your component, for example:

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

      

Note: you may need babel

and babel-preset-es2015

to use the operator spread: ...

.

+5


source







All Articles