Home > Software engineering >  How to pass Boolean props to another component in vuejs
How to pass Boolean props to another component in vuejs

Time:05-27

I have two components : component A and Component B. In the component A, I have a props calle hasBorder with Boolean type and when i call component A in the component B, i passed value to a props component of component A, i have an error.

html component A:

<div> <img src="path" :style="hasBorder ? 'border:5px;': ''"/></div>

js component A:

Vue.component('compA', {
    props: {
       hasBorder:{
                   type:Boolean,
                   default:false
                 }
    }
});

html component B:

<div> My image : <compA has-border="myStyle"></compA></div>

js component B:

Vue.component('compB', {
    data: {
       return {
           myStyle : { type:Boolean, default :true}
        } 
    }
});

I have this error "Invalid prop:type check failed for prop hasBorder". Expected Boolean, got String with value "myStyle".

How can i fix this error please

CodePudding user response:

You need to bind your props with v-bind: or : in order to pass data. Data property needs to be a function that returns object. Please take a look at snippet:

const app = Vue.createApp({
  data() {
    return {
      myStyle: true,
      myPath: 'https://picsum.photos/100'
    };
  },
})
app.component('compA', {
  template: `
    <div><img :src="path" :style="hasBorder ? 'border: 5px solid turquoise;': ''"/></div>
  `,
  props: {
    hasBorder:{
      type:Boolean,
      default:false
    },
    path: {
      type: String,
      default: ''
    }
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div> My image : <comp-a :has-border="myStyle" :path="myPath"></comp-a></div>
</div>

CodePudding user response:

You expect bool value but you are trying to send an object.

Try this

Vue.component('compB', {
    data: {
       return {
           myStyle : true
        } 
    }
});

And use v-bind

<div> My image : <compA v-bind:has-border="myStyle"></compA></div>

  • Related