Search code examples
vue.jsarrow-functions

How to access component data from inside mapState()?


Depending on the value of my prop buttonType, I want to retrieve different store variables:

...mapState({
  backgroundColor: state => this.buttonType === 'primary'
    ? state.primary_button.background_color
    : state.secondary_button.background_color
})

This doesn't work though, because arrows functions have their own this. So I tried:

...mapState({
  backgroundColor: function(state) {
    return this.buttonType === 'primary'
    ? state.primary_button.background_color
    : state.secondary_button.background_color
  }
})

Getting this error:

Expected method shorthand

What's the right way to do this?


Solution

  • I would split this into three props: primaryColor and secondaryColor (using mapState), and then a separate computed prop that returns one of them based on buttonType:

    export default {
      computed: {
        ...mapState({
          primaryColor: state => state.primary_button.background_color,
          secondaryColor: state => state.secondary_button.background_color,
        }),
        backgroundColor() {
          return this.buttonType === 'primary'
            ? this.primaryColor
            : this.secondaryColor
        }
      }
    }
    

    Or if you just want one prop, you could reference the store's state directly:

    export default {
      computed: {
        backgroundColor() {
          return this.buttonType === 'primary'
            ? this.$store.state.primary_button.background_color
            : this.$store.state.secondary_button.background_color
        }
      }
    }