0

When I change the value of my v-text-field, I can see from the Vue tab of the developer tools that the value of lastName is updated in the user store with my code below. But, for some reason, the values of my 3 tests in my template below are not updated (or synchronized). Why ? What's wrong in my code ?

pages/home.vue:

<template>
  <v-container>

    <v-container>
      <v-row>
        <v-col>
          <v-text-field v-model="lastName" />
        </v-col>
      </v-row>
    </v-container>

    TEST 1:
    {{ $store.state.user.last_name }}

    TEST 2:
    {{ lastName }}

    TEST 3:
    <v-text-field v-model="lastName" />

  </v-container>
</template>

<script>
export default {
  computed: {
    lastName: {
      get() {
        return this.$store.state.user.last_name
      },
      set(value) {
        this.$store.commit('user/UPDATE_PROP', ['last_name', value])
      }
    }
  }
}
</script>

store/user.js

export const mutations = {
  UPDATE_PROP(state, payload) {
    state[payload[0]] = payload[1]
  }
}
DevonDahon
  • 7,460
  • 6
  • 69
  • 114
  • Please share your store state and the file where you are exporting the mutation to (i.e your user module). If you could post where you initialised your store, that will also be helpful. – Tony Aug 15 '20 at 02:02
  • with watchers you could track your store changes [https://stackoverflow.com/questions/43270159/vue-js-2-how-to-watch-store-values-from-vuex](https://stackoverflow.com/questions/43270159/vue-js-2-how-to-watch-store-values-from-vuex) – arman amraei Aug 15 '20 at 07:48
  • @Tony I haven't set store `state` in my `store/user.js`, the variable is created by the mutation and setting `export const state = () => ({ last_name: '' })` explicitly doesn't fix the issue. – DevonDahon Aug 15 '20 at 07:50
  • I think that's the issue. The Vuex store state is reactive, just as the `data` property in the Vue Instance and setting the store variable in the mutation will not trigger a re-render. Please post what you have so I can see if there are corrections to be made. I strongly suspect the issue is from your setup. @DevonDahon – Tony Aug 15 '20 at 09:28
  • @Tony this is all the code I have... I'm using Nuxt. I guess my problem has to see with [this](https://vuejs.org/v2/guide/reactivity.html) but I can't figure out how to fix it. – DevonDahon Aug 15 '20 at 10:54

1 Answers1

1

I think the problem is in the way you set up your store. According to the Nuxt documentation,

you create a store directory and

every .js file inside the store directory is transformed as a namespaced module (index being the root module).

Also, according to the documentation,

... your state value should always be a function to avoid unwanted shared state on the server side.

Your state should look something like this

store/user.js

export const state = () => ({
  last_name: ''
})

export const mutations = {
  UPDATE_PROP(state, payload) {
    state[payload[0]] = payload[1]
  }
}
Tony
  • 1,414
  • 3
  • 9
  • 22