Subscribe on changes!

通过泛型参数定义props时,可选的boolean类型默认值异常

avatar
May 29th 2023

Vue version

3.3.4

Link to minimal reproduction

https://play.vuejs.org/#eNp9UbtuwzAM/BVCS1sgloZ0Mpw0Rads+QAtfjCp2ugBiU5bGP73UnEaGCmQTUeeeDzeIF5DkKceRSmq1EYTCBJSH9baGRt8JHjzNsA+egsPUmWQ6Q/aVWriM5MBoQ3HmpARQHX+o/hdqWtDLMQ0sbB1kB/JO9YcMl1fGkmLEs6VXGOVjLV4JwqpVKp34fMgW2/Vhnsq9o6MxaLzdrOUS/msOpNoXpaYbNFE/5UwsqAWi9lsxcUTxiKi6zBivKt1w53r3bT+aWbJUbuR7dNPQEmJbeP3+bTGEcZ93SJsd5Px+qWExvsj1nxUgIah623D6zFqGSWKxh2meX9hzLI71u6w0iKf8pojwCXJIcuM1ywv63CUPNq7RBCiD7CCDvfG4Y5Bqra79ePT3bCHYfo3sst53OMvU33P7g==

Steps to reproduce

  1. 通过SFC中的defineProps给子组件接收参数
  2. 通过泛型参数定义props的约束
  3. 当类型为可选的boolean时,得到的默认值是false
  4. 其他可选的基础类型都可以正常不返回

What is expected?

预期所有的可选参数在不申明的情况下不输出对应的key

What is actually happening?

类型为可选的boolean时,得到的默认值是false

System Info

No response

Any additional comments?

No response

avatar
May 29th 2023

Go to docs and read about it. if u want boolean to be undefined, make it undefined with defaults.

const props = withDefaults(defineProps<Props>(), {
  prop: undefined,

})
avatar
May 29th 2023

基于withDefaults实现当然是可以的,但是我并不希望通过这种方式主动申明,我认为可选的boolean类型应该和可选的number类型或者string类型有一样的表现,而不是直接输出false @modelair

avatar
May 29th 2023

@fisheep01 https://vuejs.org/guide/components/props.html#prop-validation check it.

我了解文档中的申明,我想表达的是为何针对boolean需要有个额外的逻辑,而不是统一的undefined行为,我觉得这样会给开发者一个额外的理解负担 在实现的时候是因为什么限制或者其他考虑吗? @modelair

avatar
May 29th 2023

@fisheep01 为了对齐原生 HTML 标签的 boolean attributes 的行为。https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML