首页 > 解决方案 > Vue.js 传递一个返回 true 或 false 作为 prop 的函数

问题描述

我正在尝试传递一个返回 true 或 false 作为道具的函数,类似于此的函数

canBeUsed(): boolean {
      if (this.usable) {
        return true
      } 
     return false
     }

我将道具传递给的组件具有以下代码

props: {
canBeUsed: {
type: Boolean
}
}

但我收到警告 Invalid prop: type check failed for prop "canBeUsed". Expected Boolean, got Function

错误是因为我传递了一个返回 true 或 false 的函数,但是代码可以正常工作。它仍然是布尔值,我只需要修复这个警告,非常感谢任何帮助,谢谢!

标签: javascriptvue.js

解决方案


我猜你正在做:

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

这确实将函数作为道具传递。但是,您的道具符合布尔值,您应该传递该函数的结果:

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

如果函数很复杂(每次模板重新渲染都会调用它),这种方法可能会导致一些性能问题。在这种情况下,最好的方法是使用计算道具。

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

这将仅在需要时重新评估道具价值。


推荐阅读