Vue3中使用render()函数返回默认<slot />的实现方法
Absolutely! You can definitely swap that minimal <template><slot></slot></template> setup out for a render function in Vue 3—this is totally feasible, and it’s actually simpler than you might think once you get the hang of how slots work in render functions.
Here’s how to do it in both options API and composition API:
1. Options API approach
If you’re using the traditional options API, you can define a render method directly in your component options. You’ll access the default slot via this.$slots.default (a function that returns an array of VNodes):
<script> export default { render(h) { // Render the default slot content; fall back to an empty array if slot is empty return h('div', {}, this.$slots.default?.() || []) } } </script>
Note: The div wrapper here is optional—if you don’t need a container element (just like your original template), you can return the slot content directly:
return this.$slots.default?.() || []
2. Composition API (with <script setup>)
In <script setup>, use useSlots() to access slot content, and defineOptions() to attach the render function to your component:
<script setup> import { h, useSlots } from 'vue' defineOptions({ render() { const slots = useSlots() // Return the default slot content, or an empty array if no content exists return slots.default?.() || [] } }) </script>
Why this works
Vue compiles templates into render functions under the hood, so your original template is essentially shorthand for the render function we wrote above. The slots.default() call retrieves the actual VNode content passed into the default slot—this is exactly what the <slot> tag does in a template.
If your component doesn’t need a wrapper element, returning the slot content directly (no container) is perfectly valid, just like your original template’s bare <slot> setup.
内容的提问来源于stack exchange,提问作者Micheal J. Roberts

