有个布尔类型的组件属性modelValue,当给这个属性传递空字符串""的时候,组件接收的值是true,我跟踪代码发现了这个地方,请问可以给解答一下这里为什么要转换成true吗?谢谢 #13129
-
Beta Was this translation helpful? Give feedback.
All reactions
Boolean props aim to behave like boolean attributes in HTML.
So, for example, the checked
attribute of a native checkbox can be set in various ways:
<input type="checkbox" checked> <input type="checkbox" checked=""> <input type="checkbox" checked="checked">
Vue handles boolean component props the same way. Imagine we have the prop checked: Boolean
, then:
<MyCheckbox checked /> <MyCheckbox checked="" /> <MyCheckbox checked="checked" />
All of these will lead to the checked
prop being set to true
. The first two will both lead to checked
being an empty string.
If you have a prop that can be either a string or a boolean then the order matters. For example, checked: [String, Boolean]
would not...
Replies: 2 comments 2 replies
-
Boolean props aim to behave like boolean attributes in HTML.
So, for example, the checked
attribute of a native checkbox can be set in various ways:
<input type="checkbox" checked> <input type="checkbox" checked=""> <input type="checkbox" checked="checked">
Vue handles boolean component props the same way. Imagine we have the prop checked: Boolean
, then:
<MyCheckbox checked /> <MyCheckbox checked="" /> <MyCheckbox checked="checked" />
All of these will lead to the checked
prop being set to true
. The first two will both lead to checked
being an empty string.
If you have a prop that can be either a string or a boolean then the order matters. For example, checked: [String, Boolean]
would not convert string values to true
, whereas checked: [Boolean, String]
would.
Beta Was this translation helpful? Give feedback.
All reactions
-
Thanks a lot! I got it
Beta Was this translation helpful? Give feedback.
All reactions
-
为了兼容dom中只用属性的这种写法 <input disabled>
不想转换直接在Boolean前面加个String就行了
Beta Was this translation helpful? Give feedback.
All reactions
-
是的,非常感谢,通过这个问题我也学到了
https://github.com/vuejs/core/issues/13099
Beta Was this translation helpful? Give feedback.