I'm trying to add or update an object to store with Vuex.
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
userData: {}
},
mutations: {
ADD_USER_DATA: (state, data) => {
state.userData.push(data)
}
}
})
This returns state.userData.push
is not a function.
And in the components:
<template>
<div>
<input type="date" v-model="inputData.date1">
<input type="date" v-model="inputData.date2">
<input type="number" v-model="inputData.date3">
<button @click="submitForm">Submit</button>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
export default {
data () {
return {
inputData: {}
}
},
computed: {
...mapState([
'userData'
])
},
methods: {
...mapMutations([
'ADD_USER_DATA'
]),
submitForm () {
this.ADD_USER_DATA(this.inputData)
}
}
}
</script>
Later on I want to update userData
with a value from other component, so that it impacts both components. I would like to have a nice way of adding, replacing, concating the old array with a new array. I followed the example in this video.
(FYI: I'm currently learning Vue.js from scratch and couldn't figure out this Vuex's mutations, actions...)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
// userData: {}
userData: []
},
mutations: {
ADD_USER_DATA: (state, data) => {
state.userData.push(data)
}
}
})
You are trying to use a push
method of Object. Object does not have a push method you should initiate userData
value with Array []
or assign that data to the object
if you need reactivity:
mutations: {
ADD_USER_DATA: (state, data) => {
Object.keys(data).forEach( key => {
Vue.set(state.userData, key, data[key])
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With