uni-app 传入默认true的Boolean类型错误

uni-app 传入默认true的Boolean类型错误

示例代码:

<van-button text="朴素按钮" :plain="true" type="primary"></van-button>  
<van-button text="朴素按钮" plain type="info"></van-button>

操作步骤:

  • 父组件传入一个Boolean类型到子组件

预期结果:

  • 支持第二种方式

实际结果:

  • 第二种报错

bug描述:

子组件中接收了一个plain的Boolean属性,最常用的方式会报错

<van-button text="朴素按钮" :plain="true" type="primary"></van-button>  
<van-button text="朴素按钮" plain type="info"></van-button>

第一种合法,第二种最常用的不合法,认为传入的是string类型的空字符


更多关于uni-app 传入默认true的Boolean类型错误的实战教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复

第二种是报错的, Expected Boolean, got String with value “”,建议用第一种写法

更多关于uni-app 传入默认true的Boolean类型错误的实战教程也可以访问 https://www.itying.com/category-93-b0.html


我就是反馈第二种报错,需要官方修的呀,Boolean基本上都是这样写的

uni-app 中,如果你需要传递一个默认值为 trueBoolean 类型参数,但在使用过程中遇到了问题,可能是由于以下几种原因导致的。以下是一些常见的解决方法:

1. Prop 定义问题

确保你在组件的 props 中正确定义了 Boolean 类型的属性,并设置了默认值为 true。例如:

export default {
  props: {
    isVisible: {
      type: Boolean,
      default: true
    }
  }
}

2. 父组件传递 Prop 问题

如果父组件传递了 falsenull,子组件的默认值将不会被使用。确保父组件传递的值是正确的。

<!-- 父组件 -->
<child-component :isVisible="false"></child-component>

在这种情况下,子组件的 isVisible 将会是 false,而不是默认的 true

3. 直接传递 Boolean 值

如果你直接在模板中传递 Boolean 值,确保使用 v-bind: 来绑定属性,否则传递的将是字符串而不是 Boolean

<!-- 正确 -->
<child-component :isVisible="true"></child-component>

<!-- 错误 -->
<child-component isVisible="true"></child-component>

4. Prop 类型检查

确保你在 props 中定义了正确的类型。如果类型不匹配,可能会导致默认值不生效。

5. 使用 v-model

如果你需要双向绑定 Boolean 值,可以使用 v-model

<!-- 父组件 -->
<child-component v-model:isVisible="isVisible"></child-component>

<!-- 子组件 -->
<template>
  <div v-if="isVisible">Visible</div>
</template>

<script>
export default {
  props: {
    isVisible: {
      type: Boolean,
      default: true
    }
  },
  emits: ['update:isVisible']
}
</script>

6. 调试

如果以上方法都无法解决问题,可以尝试在子组件中打印 props 的值,检查是否正确地接收到了默认值。

export default {
  props: {
    isVisible: {
      type: Boolean,
      default: true
    }
  },
  mounted() {
    console.log(this.isVisible); // 检查是否正确接收到默认值
  }
}
回到顶部