Vuex and dynamic states. Is possible?

≯℡__Kan透↙ 提交于 2020-01-16 18:57:22

问题


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:


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


来源:https://stackoverflow.com/questions/54811786/vuex-and-dynamic-states-is-possible

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!