A
A
alaskafx2021-11-04 21:44:22
Vue.js
alaskafx, 2021-11-04 21:44:22

Is there a better way or how can this code be improved?

I had the following task: to send changes from input (range) to different ключ:значениеones in the Vuex storage,
but the fact is that everything was distributed among objects there, and there was not one input.

The task was such that the values ​​from the sliders had to fill their own ключ:значенияin the Vuex store object.

Imagine we have a storage state like this:

state: {
CarSetup: {
      wheels: 0,
      color: 0,
      sim: 0,
    },
}

And the inputs are in a separate component.

My implementation was like this:

The component code looked like this:
data(){
  return{
     rangeValues: {
        wheels: 0,
        color: 0,
        sim: 0
      },
  }
},

computed: {
    returnValue() {
      return { ...this.rangeValues };
    },
},

watch:{
    returnValue(newValue, oldValue) {
      if(newValue.wheels!= oldValue.wheels){
        this.$store.commit('setCarInfo', {to: 'wheels', value: newValue.wheels})
      }
      if(newValue.color!= oldValue.color){
        this.$store.commit('setCarInfo', {to: 'color', value: newValue.color})
      }
      if(newValue.sim!= oldValue.sim){
        this.$store.commit('setCarInfo', {to: 'sim', value: newValue.sim})
      }
    },
}


And the setCarInfo mutation code that assigned the values ​​looked like this:

mutations: {
    setCarInfo(store, v){
      store.CarSetup[v.to] = v.value
    },
  },


I want to know from you:
is this method "not a crutch"?
Are there any better ways? (If there is, can you please tell or show?)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-11-04
@alaskafx

Cut out returnValue, make the rangeValues ​​property from the usual one calculated:

computed: {
  rangeValues() {
    return new Proxy(this.$store.state.carSetup, {
      set: (target, key, val) => {
        this.$store.commit('setCarInfo', { [key]: val });
        return true;
      },
    });
  },
},

Rewrite the mutation as follows:
setCarInfo: (state, payload) => Object.assign(state.carSetup, payload),

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question