Passing boolean Vue prop value in HTML

前端 未结 2 1605
逝去的感伤
逝去的感伤 2021-01-03 18:20

I am fairly new to Vue and have started with a project with vue-cli.

I am looking into conditional rendering based on a prop sent from parent.

Home.v

相关标签:
2条回答
  • 2021-01-03 19:07

    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">
    
    0 讨论(0)
  • 2021-01-03 19:21

    If passing in JS keywords such as boolean values or references to variables, you will need to use v-bind, 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">
    
    0 讨论(0)
提交回复
热议问题