0
votes

Is it recommended to perform state mutations inside mutation handlers, even if you aren't accessing the state through the state parameter?

Let me give you an example.

const store = new Vuex.Store({
    state: {
        foo: [{ name: 'bar' }]
    },
    mutations: {
        changeName1 (state, payload) {
          state.foo[0].name = payload.name
        },
        changeName2 (state, payload) {
          let { item, name } = payload
          item.name = name
        }
    }
})

// Inside a component
this.$store.commit('changeName1', { name: 'foobar' })

// Inside a component
this.$store.commit('changeName2', {
    item: this.$store.state.foo[0],
    name: 'foobar'
})

In the first commit, you find the object to be mutated through the state parameter.

In the second commit, the object to be mutated is found before the commit and passed in with the payload. This way makes the mutation handler more generic, it doesn't have to know how to find the object to be mutated. However, it looks "weird" because almost all of the mutation examples I've seen, access the state parameter.

I ask this because I found myself casually mutating properties of nested objects that live in the store, and wondered if I should perform all mutations inside the store. I'm talking about dead simple mutations like flipping boolean properties. Is it really worth writing the mutation boilerplate to do that?

1
looks like your code will have reactivity problem. even if you can mutate deep object outside store it won't be reactive. Vue.set should be usedJacob Goh

1 Answers

1
votes

Is it really worth writing the mutation boilerplate to do that?

Yes because you gain the ability to track what is actually going on. Mutations can be tracked manually or by a tool like the vue-devtool. It also forces you not to simply edit your store from anywhere but always through a mutation which allows you to have a generic way to input data. You also gain the ability to perform manipulations on all incoming data in the same way because of this.

This is something you shouldn't have to do because you can simply access the state in your mutation through state.foo[0]. You can simply just commit the name.

this.$store.commit('changeName2', {
    item: this.$store.state.foo[0],
    name: 'foobar'
})