【问题标题】:Vuex and dynamic states. Is possible?Vuex 和动态状态。有可能吗?
【发布时间】:2019-07-15 15:28:36
【问题描述】:

我在 Vuex 有一个商店,状态为空

const state = {
    data: {

    }
};

还有一个简单的突变用于测试以更改值或添加新数据

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

如果我对changeOrAdd 进行提交,它会被添加到状态但它没有反应性。

我做了一个简单的技巧来更改默认值

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

在突变中:

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

每次我更改或添加新值时,它看起来就像是一种反应性。

但是,有没有一种方法可以在没有“默认”变量和这个愚蠢的技巧的情况下做到这一点?

要在 store vue 中添加新数据并使其具有响应性?

谢谢

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    由于您的密钥最初未在数据中声明,Vue 无法跟踪更改。您需要使用Vue.set 响应式添加属性,请参阅change detection caveats

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

    【讨论】:

    • 谢谢,它有效。我必须这样做:如果 key 未定义,则 Vue.set(),否则 state.data[key]=value。或者它只需要一个字符,因为在@input 中被调用......我不是最好的方法,但有效。再次感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 2019-03-20
    • 2020-06-13
    • 2020-01-20
    • 2023-03-06
    • 1970-01-01
    • 2017-10-30
    相关资源
    最近更新 更多