How to set dynamic object values with Vue/Vuex?

孤街醉人 提交于 2019-12-11 05:32:13

问题


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

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.


回答1:


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

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

  • {Object | Array} target
  • {string | number} propertyName/index
  • {any} value

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

In your case it should be:

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


来源:https://stackoverflow.com/questions/58181375/how-to-set-dynamic-object-values-with-vue-vuex

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