[Vuejs]-Vue.js pass a function that returns either true or false as a prop

1👍

Change the prop type to a Function:

props: {
  canBeUsed: {
    type: Function
  }
}

2👍

I’m guessing that you are doing:

<component :can-be-used="canBeUsed"></component>

This, indeed passes the function as a prop. However, your prop qualify for a boolean one, and you should pass the result of that function instead:

<component :can-be-used="canBeUsed()"></component>

This approach can cause some performance issues if the function is complex (it will get called on every template rerendering). In this case, the best approach is to use a computed prop.

<component :can-be-used="canBeUsed"></component>
computed: {
  canBeUsed(){
     if (this.usable) {
        return true
     } 
     return false
  }
}

This will reevaluate prop value only when needed.

1👍

Why don’t you just pass this.usable to the component props?

<component :can-be-used="usable"></component>

If all your component cares about is whether or not usable is true or false, that should be it. The data processing can happen on the parent to determine this.usable‘s value.

Leave a comment