The default value problem of boolean props in vue

Original link: https://blog.rxliuli.com/p/f3564b039a28421188146aa89b52a3c0/

Scenes

Recently, other people in the group encapsulated some components based on antdv, and some boolean type props were transparently transmitted to antdv components. But in actual use, it is found that when these boolean props are not passed, the behavior of the antdv component is inconsistent with expectations.

question

For example

Component A

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 <script lang="ts" setup>
withDefaults(
defineProps<{
flag?: boolean
}>(),
{
flag: true,
},
)
</script>

<template>
<div>

</div>
</template>

Component B

 1
2
3
4
5
6
7
8
9
10
11
 <script lang="ts" setup>
import A from './A.vue'

defineProps<{
flag?: boolean
}>()
</script>

<template>
<A v-bind="$props"></A>
</template>

test use

 1
2
3
4
5
6
7
8
9
 <script setup>
import A from './A.vue'
import B from './B.vue'
</script>

<template>
<A></A>
<B></B>
</template>

rendering result

 1
2
 true
false

playground: https://play.vuejs.org/#eNqFUcFOwzAM/ZUoQtomjfbAbZRNLXCAAyDgmEtp3S4jTaIk3SZN/XecdOs2aRo9VLbfs/Pst6Op1tG6BTqjiS0M145YcK2eM8kbrYwjKamMasgoilNPHA1ANgBZAO6ZZDKJ+ynYj4mDRovcAWaEJOk8idM+zDDMMEzigUKn1NlCyYrX0coqiYp2nstooRrNBZh37biSltEZCYjHciHU5jXUnGlheqgXSyh+L9RXdutrjH4YsGDWwOiAudzU4Hr4+esNthgPYKPKViD7CvgJVonWa+xpWStLlH3CC2pfwvm4rL/t89aBtIelvFDP7AKfUTzq45XVj3LvorvQx2SHVwxunPgpclk/IB27//M2WFhCxSV8GKVtsn+sEnm9mJEfpQTkSOnm48lVr73bZH37w2WJT99oP4zRvf/npoeXr8s1TG64Wz5BlbfC2fG5QkQvaMSqVznFe50Q9kf24MT/jytgEgrHNfZtScnXQ+K/3Y58OYP+jfu9Ij+ YLBZkhH4HZeVoQrpuGBAfJpwu3v0ByAcmXQ==

Does it feel amazing, component B clearly passes all props to component A, but it renders different results. Print the value of props.flag in component B and find that it is false . This is the actual problem.

solve

Well, the current solution is to force the default value of all boolean values ​​​​to be undefined, for example

 1
2
3
4
5
6
7
8
9
10
 <script lang="ts" setup>
withDefaults(
defineProps<{
flag?: boolean
}>(),
{
flag: undefined,
},
)
</script>

In this way, the expected result can be obtained.

 1
2
 true
true

refer to

This article is transferred from: https://blog.rxliuli.com/p/f3564b039a28421188146aa89b52a3c0/
This site is only for collection, and the copyright belongs to the original author.