`render` 函数是 Vue 中用于**手动创建虚拟 DOM 节点(VNode)** 的核心机制,它提供比模板(template)更灵活、更强大的编程能力
render函数是 Vue 中用于手动创建虚拟 DOM 节点(VNode)的核心机制,它提供比模板(template)更灵活、更强大的编程能力。其类型定义为:
Type:(createElement:()=>VNode)=>VNode// 或更准确地说(含 functional context):Type:(h:CreateElement,ctx?:RenderContext)=>VNode其中:
h(常简写为createElement,Vue 2 中常用h,Vue 3 中为h函数,本质是createVNode的别名)用于创建 VNode;- 返回值必须是一个 VNode(或数组,但根节点需为单个 VNode);
- 在Vue 2 的函数式组件中,第二个参数
context提供props、children、slots、data等上下文信息; - 在Vue 3中,
render函数签名升级为(props, { slots, attrs, emit }) => VNode,且h是从vue显式导入的:import { h } from 'vue'; render函数的优先级高于任何模板(包括template选项和挂载元素内的 HTML 模板),即只要定义了render,Vue 就忽略模板编译。
✅ 示例(Vue 3):
import{h}from'vue'exportdefault{props:['msg'],render(){returnh('div',{class:'hello'},[h('h1',this.msg),h('p','This is rendered via JS!')])}}⚠️ 注意:
render函数中无法直接访问this(Vue 3 组合式 API 下需用setup()返回上下文);- Vue 3 推荐优先使用
setup()+<script setup>语法糖,render主要用于高阶组件、UI 库或特殊渲染逻辑场景。
render
Type: (createElement: () => VNode) => VNode Details: An alternative to string templates allowing you to leverage the full programmatic power of JavaScript. The render function receives a createElement method as it’s first argument used to create VNodes. If the component is a functional component, the render function also receives an extra argument context, which provides access to contextual data since functional components are instance-less. The render function has priority over the render function compiled from template option or in-DOM HTML template of the mounting element which is specified by the el option. See also: Render Functions