Vue3 是否有相当于以下 Vue2 方法:
methods: {
hasSlot(name) {
return !!this.$slots[name]
}
}
Run Code Online (Sandbox Code Playgroud)
在 Vue3 的 Composition API 中?
我试过了:
setup({slots}) {
const hasSlot = (name) => {
return !!slots[name];
}
return { hasSlot }
}
Run Code Online (Sandbox Code Playgroud)
但它没有返回预期值,因为slots未定义(控制台中的每个错误)。
小智 42
现在,在 Vue3 组合 API 中,您可以使用useSlots.
<script setup>
const slots = useSlots()
const hasSlot = (name) => {
return !!slots[name];
}
</script>
Run Code Online (Sandbox Code Playgroud)
ton*_*y19 34
正如注释中指出的,第二个参数setup()( the context)包含组件的slots. 第一个参数是组件的props.
export default {
setup(props, { slots }) {
const hasSlot = name => !!slots[name]
return { hasSlot }
}
}
Run Code Online (Sandbox Code Playgroud)
插槽也在模板中公开为$slots,因此您可以替换hasSlot(slotName)为$slots[slotName]或 只是$slots.SLOTNAME(例如,$slots.footer):
<template>
<footer v-if="$slots.footer">
<h3>footer heading</h3>
<slot name="footer" />
</footer>
</template>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20821 次 |
| 最近记录: |