0

I am assigning a variable in my component to a variable stored in vuex (let's say it's empty at the beginning) like

export default {
  name: "Step1",
  [...]
  data() {
    return {
      participants: this.$store.state.participants,
  [...]

later I work with this variable and add something like

  [...]
  methods: {
    add: function() {
      this.participants.push("foo");
    },
    [...]

I never update the variable in the store as I double-check on devtools. I expect this behaviour and expect the variable to be empty again after moving to another route and coming back. But somehow the variable in the component still contains "foo" despite the variable in the store is empty.

I'd appreciate a hint what I don't understand in Vue, it's driving me crazy.

AndreasInfo
  • 1,062
  • 11
  • 26

2 Answers2

0

You should never change the store state directly like that. As stated in the docs:

The only way to actually change state in a Vuex store is by committing a mutation.

So in your store, you have to add a mutation method, like so:

mutations: {
    addParticipant(state, participant) {
      state.participants.push(participant);
    }
}

And call that: this.$store.commit('addParticipant', 'Foo')

Brother Woodrow
  • 6,092
  • 3
  • 18
  • 20
  • Actually I was thinking to get the variable from the store, use it in the html (v-for or whatever), change it (add or whatever) and finally update the store like you suggested with this.$store.commit('updateParticipants', this.participants'). Is this a wrong approach? – AndreasInfo Dec 30 '20 at 12:33
  • Not really! You could just make a local copy (`participants: [...this.$store.state.participants]` will copy the store array), edit that, and then update the store later. – Brother Woodrow Dec 30 '20 at 19:15
0

Thanks to some help here I found a workaround:

Make a local copy of the variable in the component, e.g. with using spread syntax for iterable objects and simple assignments for primitive datatypes, and update the whole object after working with it.

Check this to for get an understanding for call-by-value and call-by-reference in JavaScript: stackoverflow.com/a/6605700/381282

<template>
  [...]
</template>

<script>
export default {
  name: "Step1",
  [...]
  data() {
    return {
      participants: [...this.$store.state.participants]
  [...]
  methods:
    updateParticipants: function() {
      $store.commit('updateParticipants', this.participants)
  [...]
<script>
AndreasInfo
  • 1,062
  • 11
  • 26