Vue 3是否支持继承组件并向插槽追加内容(类似super()用法)
Vue 3 怎么扩展组件插槽的默认内容?
Vue 3 不支持你尝试的 {{super()}} 写法,但有对应的办法在重写具名插槽时保留它的默认内容。
办法一:用 useSlots 组合式 API
在 <script setup> 里通过 useSlots 获取插槽对象,就能渲染原插槽的默认内容:
ComponentA.vue 保持不变:
<template> <div> <slot name="ctrl"> <span>Default</span> </slot> </div> </template>
App.vue 修改为:
<template> <ComponentA> <template #ctrl> <!-- 先渲染原插槽的默认内容 --> <component :is="slotDefault" /> <span>Extra</span> </template> </ComponentA> </template> <script setup> import { useSlots } from 'vue' const slots = useSlots() // 拿到ctrl插槽的默认内容渲染函数 const slotDefault = slots.ctrl?.default?.() </script>
办法二:用渲染函数
如果不用 <script setup>,可以直接写渲染函数调用 renderSlot:
<script> import { h, renderSlot } from 'vue' import ComponentA from './ComponentA.vue' export default { components: { ComponentA }, render() { return h(ComponentA, null, { ctrl: () => [ // 先渲染原插槽默认内容 renderSlot(this.$slots, 'ctrl'), h('span', null, 'Extra') ] }) } } </script>
为啥不能用 super()?
Vue 的插槽机制和类继承里的 super 完全不是一回事,super() 是类中调用父类方法的语法,而插槽是父组件向子组件分发内容的机制,所以 Vue 根本没提供这种直接写法。
内容的提问来源于stack exchange,提问作者Thomas
相关产品推荐
相关产品推荐

