3

I have a component that is going to have data named isVendorOrAgent that should be false or true based on a property that the component gets. When I put this condition on the data section of the component, it doesn't work and always returns false but when I put that in created() and change the isVendorOrAgent in created(), it works.

How can I make this work?

This is the condition that is not working:

data : () => {
   return {
      isVendorOrAgent : (this.entityName == "vendor" || this.entityName == "agent") ? true : false;
   }
}

but this works when the default is false:

created(){
    if(this.entityName == "vendor" || this.entityName == "agent"){
      this.isVendorOrAgent = true;
    }
  }
BSMP
  • 4,596
  • 8
  • 33
  • 44
Hamid
  • 679
  • 1
  • 7
  • 22
  • 1
    Defining `data` as an arrow function is a nono. https://vuejs.org/v2/api/#data https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback – Eric Guan Aug 29 '18 at 05:23
  • thank you @EricGuan – Hamid Aug 29 '18 at 08:06

1 Answers1

4

Try this code sample:

data () {
  return {
    isVendorOrAgent: Boolean(this.entityName === "vendor" || this.entityName === "agent")
  }
}

What is different?

  1. Now data is not an arrow function, because arrow functions do not change the context, so this won't be what it should be inside the component
  2. We now store a Boolean value
  3. We are now using strict equality ===, which is just a good habit

You may also take a look at computed properties: https://v2.vuejs.org/v2/guide/computed.html

Your problem could be solved like this:

computed () {
  return {
    isVendorOrAgent: Boolean(this.entityName === "vendor" || this.entityName === "agent")
  }
}

The second way is preferable if you need this property to be reactive.

tony19
  • 125,647
  • 18
  • 229
  • 307
sobolevn
  • 16,714
  • 6
  • 62
  • 60
  • 1
    I think even if it should not be reactive computed is the better way to go. Thanks for the answer i wouldve suggested him the same. – niclas_4 Aug 29 '18 at 06:41
  • 1
    This is the answer. It must be in computed to be reactive and the misuse of arrow in data hook – gil Aug 29 '18 at 06:53