Nszz
Nszz

Reputation: 145

component not handling empty prop

I have a component data.table.vue and other components for eg abc.vue and xyz.vue.

inside this data.table.vue, a paragraph to render depending on the prop received by the it.. However, not both my components abc.vue and xyz.vue will send props.. only abc.vue needs to send props.. for eg:

in abc.vue:

<template>
   <data-table 
     :isShown=true
   <data-table>
</template>

and in xyz.vue no props

<template>
   <data-table 
   </data-table>
</template>

and in data.table.vue

 <p v-if="isShown"> hello world </p>

but I want this paragraph to be always shown for xyz component.. and only for abc.vue, i want this paragraph to render according to the props isShown.. However, even in xyz.vue , its being rendered depending on the props sent in abc.vue..

Please help ..

Upvotes: 0

Views: 717

Answers (2)

Johnny
Johnny

Reputation: 205

For Vue3 with the composite API you can set default props like this:

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  props: {
    isShown: {
      type: boolean,
      default: true
    },
  },
  setup() {},
})
</script>

And with the script setup

<script setup lang="ts">
const props = withDefaults(
  defineProps<{
    isShown: boolean
  }>(),
  {
    isShown: true
  }
)
</script>

Upvotes: 0

Noah Porfido
Noah Porfido

Reputation: 126

You can set a default prop like this.

   export default {
     props: {
        isShown: {
        type: Object,
        default: true
       }
    }
}

Default will be taken when no props are passed.

Upvotes: 3

Related Questions