Home > Software engineering >  How to have an if/else statement in a computed/methods property block for VueX?
How to have an if/else statement in a computed/methods property block for VueX?

Time:10-13

I have a variable passed into a component called "store". This will store the name of the store that needs to be used in the component. This component just needs to make sure to get the data from the proper store.

computed: {
   if (this.store === "storeNumber1")
      ...mapGetters(this.store, ["thing1", "thing2"]),
   else if(this.store === "storeNumber2") 
       ...mapGetters(this.store, ["thing1", "thing2"]),


}
props: {
 store
} 

This does not work. What would I need to make this concept work? And what about for Vue Mutations? Thank you.

CodePudding user response:

mapGetters isn't meant to be used in a reactive way based on a prop.

Instead, you should use the longhand syntax to access the namespaced getter from the this.$store.getters object:

this.$store.getters[__MODULE_NAME__   '/'   __GETTER_NAME]

Use that syntax in a computed property for each getter:

export default {
  props: {
    store: {
      type: String,
      required: true,
    },
  },
  computed: {
    thing1() {
      return this.$store.getters[this.store   '/thing1']
    },
    thing2() {
      return this.$store.getters[this.store   '/thing2']
    },
  },
}

demo

CodePudding user response:

Yes, this does not work. computed properties need to be functions with a simple return. What you want need to be compined between computed and methods:

methods: {
   myFunction() {
      if (this.store === "storeNumber1") {
         return ...mapGetters(this.store, ["thing1", "thing2"])
      }
      else if(this.store === "storeNumber2") {
         return ...mapGetters(this.store, ["thing1", "thing2"])
      }
   }
}

computed: {
   myComputedProperty() {
      return this.myFunction()
   }
}

props: {
 store
} 
  • Related