简体   繁体   中英

How to set dynamic object values with Vue/Vuex?

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. PS They also have to be reactive.

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 (eg this.myObject.newProperty = 'hi').

But the function arguments looks like this

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

https://v2.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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM