Reputation: 1333
I'm coordinating input elements with the keys of an object on Vuex state. Let's say I've got this object:
myObj: { foo: 1, bar: 2 }
And a computed property in a component:
myObjVals: {
get(){ return this.$store.state.myObj },
set(//?) { //? },
},
In the template, I can get values from the store:
<input type="number" v-model="myObjVals['foo']"/> // displays "1"
<input type="number" v-model="myObjVals['bar']"/> // displays "2"
But when I adjust the value on an input, I get the error: "Do not mutate vuex store state outside mutation handlers."
One obvious solution here is to have a different computed property for each key in myObj
... but for larger objects, this gets repetitious/cumbersome. I am wondering if there is any way to code this as I am attempting to above, that is, using only one computed property to reference the object for both get
and set
functions in v-model
.
Upvotes: 6
Views: 3943
Reputation: 5987
Come to think of your problem once more. One solution could be something suggested here: https://vuex.vuejs.org/guide/forms.html
<input type="number" :value="myObjVals['foo']" @input="changeMyObj('foo', $event)"/> // displays "1"
<input type="number" :value="myObjVals['bar']" @input="changeMyObj('bar', $event)"/> // displays "2"
with computed property and a method:
computed: {
myObjVals: function () {
return this.$store.state.myObj
}
},
methods: {
changeMyObj(key, evt) {
this.$store.commit('changeMyObj', {key: key, value: evt.data})
}
}
With a mutation inside the store:
mutations: {
changeMyObj(state, objInput) {
state.myObj[objInput.key] = objInput.value
}
}
Here is a "working" fiddle: http://jsfiddle.net/zfab6tzp/346/
Not sure if this is the best solution possible, but it seems to be working
Upvotes: 6