0
votes

Suppose a store like this

...
state: {
    filters: {
        a: '',
        b: ''
    }
},
mutations: {
    updateFilters(state, newObject) {
        state.filters = newObject
    }
}
...

And a component like this

...
<input v-model='filters.a'></input>
...
computed: {
    filters: {
        get() {
            this.$store.state.filters
        }
        set(value) {
            this.$store.commit('updateFilters', value)
        }
    }
}
...

Everything works fine but I see a warning saying

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

So I'm obviously missing something

I don't understand how to handle this. Can someone explain how to mutate a state object in a component?

I know, I can mutate every filters prop, but I have a LOT of filters in that object, so mutate every single prop is not the best solution in this case.

1
if you do state.filters ={newObject} you are getting the same warning?Raffobaffo
Is ES6 Shorthand sintaxRaffobaffo
You can use a generic mutator which will have 2 arguments - the object key to mutate (your filter) and the value to be set.IVO GELOV

1 Answers

0
votes

The problem is that your setter never gets called. The getter is used, but a is updated directly.

Here is one option:

<input :value="filters.a" @input="updateFilterA"></input>
...
computed: {
  filters() {
    return this.$store.state.filters /* or mapState */
  }
},
methods: {
  updateFilterA(value) {
    this.$store.commit("updateFilterA", value)
  }
}

And in the store:

mutations: {
  updateFilterA(state, newValue) {
    state.filters.a = newValue
  }
}