Vue3 检查插槽是否为空

时间:2021-06-30 00:58:08

标签: vue.js vuejs3

是否有 Vue3 等效于以下 Vue2 方法:

methods: {
   hasSlot(name) {
      return !!this.$slots[name]
   }
}

在 Vue3 的 Composition API 中?

我试过了:

setup({slots}) {
   const hasSlot = (name) => {
      return !!slots[name];
   }

   return { hasSlot }

}

但它没有返回预期值,因为 slots 未定义(控制台中的每个错误)。

1 个答案:

答案 0 :(得分:1)

正如 comments 中所指出的,setup()'s second argumentcontext)包含组件的 slots。第一个参数用于组件的 props

export default {
  setup(props, { slots }) {
    const hasSlot = name => !!slots[name]
    return { hasSlot }
  }
}

demo 1

插槽在模板中也公开为 $slots,因此您可以将 hasSlot(slotName) 替换为 $slots[slotName] 或仅替换为 $slots.SLOTNAME(例如,$slots.footer):

<template>
  <footer v-if="$slots.footer">
    <h3>footer heading</h3>
    <slot name="footer" />
  </footer>
</template>

demo 2