Y.Futekov
Y.Futekov

Reputation: 544

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! P.S. They also have to be reactive.

Upvotes: 2

Views: 2420

Answers (1)

dreijntjens
dreijntjens

Reputation: 4825

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

Upvotes: 3

Related Questions