组件不处理空道具

component not handling empty prop

我有一个组件 data.table.vue 和其他组件,例如 abc.vue xyz.vue.

在此 data.table.vue 中,根据它接收到的 prop 渲染一段。但是,我的组件 abc.vuexyz.vue 将发送 props.. 只有 abc.vue 需要发送 props.. 例如:

在abc.vue中:

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

并且 xyz.vue 没有道具

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

并在 data.table.vue

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

但我希望此段始终针对 xyz 组件显示。 并且仅针对 abc.vue,我希望根据道具 isShown 呈现该段落。但是,即使在 xyz.vue ,它的渲染取决于 abc.vue..

中发送的道具

请帮忙..

您可以像这样设置默认道具。

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

不传props时,取默认

对于 Vue3 与复合 API 你可以像这样设置默认道具:

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

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

以及脚本设置

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