You can pass boolean
by coercing it, put !!
before the variable.
let isRequired = '' || null || undefined
<input :required="!!isRequired"> // it will coerce value to respective boolean
But I would like to pull your attention for the following case where the receiving component has defined type
for props. In that case, if isRequired
has defined type to be string
then passing boolean
make it type check fails and you will get Vue warning. To fix that you may want to avoid passing that prop, so just put undefined
fallback and the prop will not sent to component
let isValue = false
<any-component
:my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>
Explanation
I have been through the same problem, and tried above solutions !!
Yes, I don't see the prop
but that actually does not fulfils what required here.
My problem -
let isValid = false
<any-component
:my-prop="isValue ? 'Hey I am when the value exist': false"
/>
In the above case, what I expected is not having my-prop
get passed to the child component - <any-conponent/>
I don't see the prop
in DOM
but In my <any-component/>
component, an error pops out of prop type check failure. As in the child component, I am expecting my-prop
to be a String
but it is boolean
.
myProp : {
type: String,
required: false,
default: ''
}
Which means that child component did receive the prop even if it is false
. Tweak here is to let the child component to take the default-value
and also skip the check. Passed undefined
works though!
<any-component
:my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>
This works and my child prop is having the default value.
null
,undefined
, orfalse
”, which is different from a JS script evaluating to false. This means an empty string is falsy in JavaScript, but would still add the attribute to DOM. To prevent that you could tryv-bind:name="name || false"
– Denilson Sá Maiafalse
to child component via a prop? – Bruce Sun'false'
. In other cases when you need to control presence of non-boolean html attribute on the element you can use conditional rendering withv-if
as suggested here: github.com/vuejs/vue/issues/7552#issuecomment-361395234 – AlexanderBattribute
but NOTprop
. We can safely pass explicitfalse
via a component property but NOT attribute (which is not recognised as a property). Am I correct? – Bruce Sun