You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3中使用render()函数返回默认<slot />的实现方法

Can I replace a slot-only template with a render function in Vue 3?

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 18:54:07