是否存在与以下Vue3方法等效的Vue2:
methods: {
hasSlot(name) {
return !!this.$slots[name]
}
}在Vue3的合成API中?
我试过:
setup({slots}) {
const hasSlot = (name) => {
return !!slots[name];
}
return { hasSlot }
}但是它没有返回期望值,因为slots是未定义的(控制台中的每个错误)。
发布于 2021-06-30 20:43:26
正如评论中指出的,罗氏 ( context)包含组件的slots。第一个参数是组件的props。
export default {
setup(props, { slots }) {
const hasSlot = name => !!slots[name]
return { hasSlot }
}
}模板中的插槽也是以$slots的形式公开的,因此您可以用$slots[slotName]或仅用$slots.SLOTNAME (例如,$slots.footer)替换hasSlot(slotName):
<template>
<footer v-if="$slots.footer">
<h3>footer heading</h3>
<slot name="footer" />
</footer>
</template>发布于 2022-05-20 08:52:07
现在,在Vue3组合API中,您可以使用useSlots。
<script setup>
const slots = useSlots()
const hasSlot = (name) => {
return !!slots[name];
}
</script>https://stackoverflow.com/questions/68187278
复制相似问题