Search code examples
javascriptvue.jsvuex

Vuex v-model to an object state field


I have a Vuex state, like this (it also has a getter, named configs:

configs: {

    1303401: {

        exampleValue: 'test'

    }

}

I also have an input where I v-model the exampleValue from the Vuex store's state:

<input type="text" v-model="config.exampleValue" />

Here is the computed property I use to return the config:

config: {

    get () {

        return this.$store.getters.configs[1303401]

    },
    set (value) {

        //this should set the configs[1303401] field with the updated exampleValue
        this.$store.dispatch('UPDATE_CONFIG', value)

    }


}

The input's value changes to the value of config.exampleValue, so the computed data is not undefined, but the Vuex state does not update.

Also if I try to console.log the value in the setter, nothing appears in the console, so the setter isn't even executed

It is probably because it is not setting the config computed property, but the config.exampleValue, but I have no idea, how to handle that.

As @asi-ple mentioned above, changing the get to return configs[1303401].exampleValue would work, but the problem is, that the config has more fields, and the page has more inputs, and I'd need to create a computed property for all fields this way.


Solution

  • Actually you can make some logic here if you have more than fields.

    Lets say that you have

    configs: {
        1303401: {
            exampleValue: 'test',
            exampleValue2: 'test2',
            exampleValue3: 'test3',
            ...
        } 
    }
    

    Than you should change template to that:

    <input type="text" :value="config[1303401].exampleValue1" @input="update_config($event, 'exampleValue1')" />
    <input type="text" :value="config[1303401].exampleValue2" @input="update_config($event, 'exampleValue2')" />
    <input type="text" :value="config[1303401].exampleValue3" @input="update_config($event, 'exampleValue3')" />
    

    And your methods like this

    methods:{
        update_config($event, where){
              this.$store.commit("UPDATE_CONFIG", {value: $event.target.data, where: where})
        }
    }
    

    Then your mutation handler looks this

    UPDATE_CONFIG(state, payload){
           state.configs[1303401][payload.where] = payload.value
    }
    

    Basically above code, your making a config data in your state which should use two-way data binding in your template. Then you are creating your inputs :value working like get methods, and @input listener is working like set methods, then update_config is committing your changes and mutation handler setting them with right place