Vue3 检查插槽是否为空

问题描述 投票:0回答:3

有没有一个Vue3相当于下面的Vue2方法:

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

在 Vue3 的 Composition API 中?

我已经尝试过:

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

   return { hasSlot }

}

但它没有返回预期值,因为

slots
未定义(控制台中出现每个错误)。

vue.js vuejs3
3个回答
47
投票

现在,在 Vue3 组合 API 中,您可以使用

useSlots

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

38
投票

正如comments中指出的,

setup()
第二个参数
context
)包含组件的
slots
。第一个参数用于组件的
props

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

演示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>

演示2


0
投票

您还可以使用 vue 中的 getCurrentInstance 来提供以下信息:- attrs、appContext、slots、props、refs 等

示例:-

    <template>
    <slot name="header"></slot>
    </template>
    <script>
import { getCurrentInstance, onMounted } from 'vue';

export default {
  name: 'MyComponent',
  setup() {
    const instance = getCurrentInstance();

    onMounted(() => {
      // Check for the presence of named slots
      if (instance.slots.header) {
        console.log('Header slot is present');
      } else {
        console.log('Header slot is not present');
      }
    });
  }
};
</script>



 <template>
  <MyComponent>
    <template v-slot:header>
      <h1>Header Content</h1>
    </template>
  </MyComponent>
</template>
© www.soinside.com 2019 - 2024. All rights reserved.