简体   繁体   中英

Vue.js - Add or set new data to object in store

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])
    })
  }

I've ended up using Object.assign method.

  mutations: {
    ADD_USER_DATA: (state, data) => {
      // state.userData.assign(data)
      state.userData = Object.assign({}, data)
    }
  }

Try it

 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.date1 = data.date1 state.userData.date2 = data.date2 } } })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM