Vue 模板被编译为返回虚拟 DOM 的 render 函数。通常你编写模板,但当你需要 JavaScript 的全部力量 来以编程方式生成 UI 时,可以直接编写 render 函数(或 JSX)。
一个 render 函数
js
{ h } ;
{
: [],
() {
(, slots.());
},
};
h(tag, props, children) 命令式地构建 vnodes。这里标题级别在运行时计算以选择 h1–h6 — 用模板语法会很笨拙。
export default {
props: ["items"],
setup(props) {
return () => (
<ul>
{props.items.map((item) =>
item.visible ? <li key={item.id}>{item.name}</li> : null
)}
</ul>
);
},
};
JSX 让你使用纯 JS(.map、条件、变量)来构建树 — 对 React 开发者来说很熟悉,对高度动态的结构更灵活。
✓ Programmatic structure: a tag/component decided at runtime (dynamic headings, schema-driven UI)
✓ Highly conditional or recursive rendering hard to express with v-if/v-for
✓ Building reusable component libraries / higher-order components
✓ Rendering based on complex JS logic where template directives feel clumsy
✓ Almost all app UI — templates are more readable, optimized by the compiler,
and benefit from compile-time hints (static hoisting, patch flags) for performance
✓ Better tooling: IDE highlighting, type-checking, easier for the whole team
值得注意的是,模板编译器添加了 性能优化(它知道什么是静态的、什么是动态的),而手写的 render 函数无法自动获得这些优化。
模板是正确的默认选择 — 可读性好、工具友好且编译器优化。
但 render 函数/JSX 是当 UI 必须 以编程方式 生成时的逃生舱(动态标签、递归树、库组件),这时模板语法会变得复杂。
知道两者都存在 — 以及模板对典型应用代码更优先,而 render 函数适合动态/库场景 — 让你在不强制统一方式的情况下选择正确的工具。