如何使用 Vue/Vuex 设置动态对象值? [英] How to set dynamic object values with Vue/Vuex?

查看:80
本文介绍了如何使用 Vue/Vuex 设置动态对象值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力理解如何动态创建 &使用 Vue/Vuex 在我的状态中的对象中填充键:值对,这是一个示例:dataObject:{}(处于状态),以及创建新键值对的突变:

I'm struggling to understand how to dynamically create & populate a key: value pairs in an object in my state using Vue/Vuex, here's an example: dataObject: {} (in state), and a mutation that creates the new key:value pairs:

  setdataObjectProps: (state, payload) => {
    for (let [key, value] of Object.entries(
      state.dataObject
    )) {
      if (key == payload[0]) {
        dataObject.total_operation_time = payload[1];
        dataObject.machine_name = payload[2];
      }
    }
  },

此解决方案有效,但键值对应该已经存在于对象中(我已将它们设置为空字符串).我尝试使用 Vue.set() 像这样:

This solution works, but the key:value pairs should already be existing in the object (i've set them to empty strings). I tried using Vue.set() like this:

Vue.set(dataObject.total_operation_time,  payload[1]);
Vue.set(dataObject.machine_name,  payload[2]);

但是,如果我理解正确的话,我很难理解如何使它工作,因为它需要第二个参数,即索引/名称.有人可以像我五岁一样解释一下如何使其工作而不必先在对象中创建键:值对吗?提前致谢!附言他们还必须是被动的.

However, i'm struggling to understand how to make it work since it expects second parameter that's the index/name, if i understand correctly. Can someone explain like i'm five how can i make it work without having to first create the key:value pairs in the object? Thanks in advance! P.S. They also have to be reactive.

推荐答案

Vue set 应该做的只有你以错误的方式使用它:

Vue set should do the work only your using it the wrong way:

向反应式对象添加一个属性,确保新的属性是也是反应性的,因此会触发视图更新.这必须用于添加新的响应式对象的属性,因为 Vue 无法检测正常属性添加(例如 this.myObject.newProperty = 'hi').

Adds a property to a reactive object, ensuring the new property is also reactive, so triggers view updates. This must be used to add new properties to reactive objects, as Vue cannot detect normal property additions (e.g. this.myObject.newProperty = 'hi').

但是函数参数看起来像这样

But the function arguments looks like this

  • {对象 |数组} 目标
  • {字符串 |number} 属性名称/索引
  • {any} 值

https://vuejs.org/v2/api/#Vue-set

在你的情况下应该是:

Vue.set(state.dataObject, 'total_operation_time',  payload[1]);
Vue.set(state.dataObject, 'machine_name',  payload[2]);

这篇关于如何使用 Vue/Vuex 设置动态对象值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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