Adam Hopkins
Adam Hopkins

Reputation: 7102

Vuex not updating computed variable mapped using mapState

I looked at several questions to figure out what I am doing wrong. Everything looks to me setup correctly.

GOAL

Based upon the value of COMPONENT A change hide/display content using v-show in DEPENDENT COMPONENT.

PROBLEM

Inside TextField Component, there is an input that triggers a mutation on my vuex store. Dependent Component has a computed value that listens to changes on the vuex store.

When typing in my TextField Component, I can verify by using the Vue.js extension that the mutations are triggering as expected.

HOWEVER, there is no change on the page.

COMPONENT A

<template>
  <div class="field">

    <input type="text" :name="field.name" v-bind:value="value" v-on:input="updateValue($event.target.value)">

  </div>
</template>

<script>
export default {
  props: ['field'],
  methods: {
    updateValue: function (value) {
      this.$store.commit('UPDATE_USER_INPUT', {'key': this.field.name, 'value': value})
    }
  }
}
</script>

MUTATION

UPDATE_USER_INPUT (state, payload) {
  state.userInput[payload['key']] = payload['value']
}

DEPENDENT COMPONENT

<template>
  <div class="field-item">
    {{ userInput }}
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  computed: {
    ...mapState([
      'userInput'
    ])
  }
}
</script>

No matter what I try, {{ userInput }} remains empty: {} until I navigate my route back to the same location. But there is no computed value listener being triggered.

Upvotes: 6

Views: 9044

Answers (1)

GuyC
GuyC

Reputation: 6574

If you are setting a new key within the vuex state then you will need to use:

UPDATE_USER_INPUT (state, payload) {
  Vue.set(state.userInput, payload.key, payload.value)
}

Otherwise it won't be reactive.

See documentation.

Upvotes: 28

Related Questions