MongoLato
MongoLato

Reputation: 381

Why can't I assign a property to an object using bracket notation + a variable?

I'm very new to Vuex, and trying to assign a value to a Vuex state, (state.map.status.isReady for this one).

However, I want to make my code reusable, so I created a function changeMapStatus(state, key, value) in order to achieve that.

This function modifies the property state.map.status.key to value it received.

However, when I call the mutation with this.$store.commit('changeMapStatus', 'isReady', true) from a component file, it simply removes the state.map.status.isReady and that property becomes undefined.

On the another hand, if I change the function to

changeMapStatus(state, value) {
  state.map.status.isReady = value;
}

it somehow works.

Can you help me which point I get it wrong?

Thanks so much!


store.js (Vuex)

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    map: {
      status: {
        isReady: false,
      },
    },
  },
  mutations: {
    changeMapStatus(state, key, value) {
      state.map.status[key] = value;
    }
  },
});

Upvotes: 3

Views: 591

Answers (2)

ZaidRehman
ZaidRehman

Reputation: 1751

According to Vuex official docs, mutation takes 2 parameters state and payload. You can use the spread operator to get values from the payload.

changeMapStatus(state, {key, value}) {
  state.map.status[key] = value;
}

this.$store.commit('changeMapStatus', {key: 'isReady', value: true})

Or else you can use it like this

changeMapStatus(state, payload) {
  state.map.status = {
      ...state.map.status,
      ...payload,
  }
}

this.$store.commit('changeMapStatus', { isReady: true });

Upvotes: 1

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You could pass an object as parameter that contains key and value as follows :

changeMapStatus(state, myObj) {
  state.map.status[myObj.key] = myObj.value;
}

and call it like:

this.$store.commit('changeMapStatus', {key:'isReady', value:true})

Upvotes: 1

Related Questions