Vuex 和动态状态.有可能吗? [英] Vuex and dynamic states. Is possible?

查看:34
本文介绍了Vuex 和动态状态.有可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Vuex 有一个空状态的商店

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

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

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

在突变中:

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?

要在商店 vue 中添加新数据并使其具有反应性?

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

谢谢

推荐答案

由于您的键最初未在数据中声明,Vue 无法跟踪更改.您需要使用 Vue.set 来被动地添加属性,请参阅 更改检测警告:

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

这篇关于Vuex 和动态状态.有可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆