Search code examples
vue.jsvuex

Vue + Vuex: variable stored in component saves changes even after leaving and coming back


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.


Solution

  • 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>