Passing boolean Vue prop value in HTML
To use a Boolean
type as a prop, you have to use v:bind
<Header v-bind:have-banner="true" page-title="Home">
or using a short syntax
<Header :have-banner="true" page-title="Home">
If passing in JS keywords such as boolean values or references to variables, you will need to use v-bind
(or :
), i.e.:
<Header v-bind:have-banner="true" page-title="Home">
This will have the effect of binding the boolean true
to the prop, not a "true"
string. If you are not using v-bind
, the haveBanner
prop will always be truthy because it is a string of non-zero length, no matter if you assign "true"
or "false"
to it.
Friendly hint: HTML tags are not case-sensitive, so you might want to use custom-header
or my-header-component
instead of Header
:
<custom-header v-bind:have-banner="true" page-title="Home">
See proof-of-concept:
Vue.component('custom-header', {
template: '#customHeader',
props: {
haveBanner: Boolean,
pageTitle: String
}
});
new Vue({
el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.15/vue.min.js"></script>
<div id="app">
<custom-header v-bind:have-banner="true" page-title="Home"></custom-header>
<custom-header v-bind:have-banner="false" page-title="Home"></custom-header>
</div>
<script type="text/x-template" id="customHeader">
<header>
<div v-if="haveBanner">
<code>haveBanner</code> is true!
</div>
<div v-else>
<code>haveBanner</code> is false!
</div>
</header>
</script>
Pro tip: Use :
shorthands to make your template more readable, i.e.:
<custom-header :have-banner="true" page-title="Home">