Skip to content
Advertisement

Accessing Vuex in v-bind

I would like to access a value from a Vuex store module within v-bind.

<input @blur="validate_field" 
       name="firstName" 
       placeholder="First Name" 
       :class="{fail: this.$store.state.formStore.signupForm.errors.firstName}"
/>

This throws the following error:

TypeError: Cannot read property 'signupForm' of undefined

I have tried adding the following:

computed: {
  ...mapState({
    signupForm: state => state.formStore.signupForm
  })
}

And replacing the failing line with:

:class="{fail: signupForm.errors.firstName}"

as well as a panoply of other things, to no avail. Any ideas?

EDIT: Here is my store:

const state = {
  // data
  formStore: {
    // data
    signupForm: {
    // data
      errors: {
        // NO data
      }
    }
  }
}

Advertisement

Answer

Thanks to @wes in the comments for pointing out the doc on reactivity.

Here the doc says:

Due to the limitations of modern JavaScript (and the abandonment of Object.observe), Vue cannot detect property addition or deletion.

I was dynamically populating the error object. Turns out Vue.js doesn’t detect this and as such can’t react to it.

With the addition of firstName, it works:

const state = {
  // data
  formStore: {
    // data
    signupForm: {
    // data
      errors: {
        firstName: ''  <--------
      }
    }
  }
}

The lesson is: all properties you expect Vue to react to must be declared explicitly.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement