Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if prop is present in Vue?

I have a component like this:

<vue-component show></vue-component>

As you can see that there is a show prop. I couldn't use typeof because it's always undefined as there's no value. Please help!

like image 379
Damon Avatar asked Jan 27 '23 02:01

Damon


2 Answers

Well, you will use like the following in the template:

<div v-if="show">
...
</div>

If you need to check inside the script, you may know like:

if(this.show) {

And,

typeof show // will always be undefined

Because props can also be accessed using this:

typeof this.show // will return Boolean as you're just passing show
// which is simply like `:show="true"`
like image 183
Bhojendra Rauniyar Avatar answered Jan 29 '23 17:01

Bhojendra Rauniyar


As an addendum to Bhojendra Rauniyar's answer you should probably set the default to false:

Vue.component('my-component', {
  //props:['show'] <--- Wont work
  props: {
      'show': { 
          type: Boolean, 
          default: false
       } 
  },  
  template: `<div>show is: {{show}}</div>`
})

new Vue({
  el: '#app',
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <my-component show></my-component>
</div>
like image 36
Soth Avatar answered Jan 29 '23 15:01

Soth