0
votes

I have a store in Vuex with an empty state

const state = {
    data: {

    }
};

And a simple mutations for test to change value or add new data

const mutations = {
    changeOrAdd(state, {key,value}) {
        state.data[key] = value;
    }
};

If I do a commit to changeOrAdd, it is added to state BUT it doesn't have reactivity.

I did a simple trick to change a default value

const state = {
    data: {
        change: 0
    }
};

And in the mutation:

const mutations = {
    changeValueAttr(state, {
        key,
        value
    }) {
        state.data[key] = value;
        state.data.change++;
    }
};

And everytime I change or add a new value, it looks like a reactivity.

But, exists a way to do this without a "default" variable and without this stupid trick?

To add a new data in store vue and make it with reactivity?

Thanks

1

1 Answers

10
votes

Since your keys initially are not declared in data, Vue can't track the changes. You need to use Vue.set to reactively add properties, see change detection caveats:

import Vue from 'vue'

const mutations = {
    changeOrAdd(state, {key, value}) {
        Vue.set(state.data, key, value)
    }
}