Template-urile Vue sunt compilate în render functions care returnează DOM virtual. De obicei scrii template-uri, dar poți scrie direct render function (sau JSX) când ai nevoie de puterea completă a JavaScript pentru a genera UI-ul programatic.
O render function
import { h } from "vue"; // h = hyperscript: creates a virtual DOM node
export default {
props: ["level"],
setup(props, { slots }) {
// dynamically choose the tag — hard to express in a template
return () => h(`h${props.level}`, slots.default());
// <DynamicHeading :level="2"> → renders an <h2>
},
};
h(tag, props, children) construiește vnodes imperativ. Aici nivelul heading-ului este calculat la runtime pentru a alege h1–h6 — incomod cu sintaxa template.
JSX (cu plugin-ul Vue JSX)
export default {
props: ["items"],
setup(props) {
return () => (
<ul>
{props.items.map((item) =>
item.visible ? <li key={item.id}>{item.name}</li> : null
)}
</ul>
);
},
};
JSX îți permite să folosești JS simplu (.map, condiționali, variabile) pentru a construi arborele — familiar pentru dezvoltatorii React și mai flexibil pentru structuri foarte dinamice.
Când render functions / JSX merită efortul
✓ 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
Când să rămâi cu template-uri (implicit)
✓ 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
Notabil, compilatorul de template adaugă optimizări de performanță (știe ce este static versus dinamic) pe care render functions scrise manual nu le obțin automat.
De ce este important
Template-urile sunt implicit corect — citibile, prietenoase cu instrumentele și optimizate de compilator.
Dar render functions/JSX sunt ieșirea de scăpare când UI trebuie generat programatic (etichete dinamice, arbori recursivi, componente de bibliotecă) unde sintaxa template devine contorsionată.
Știind că ambele există — și că template-urile sunt preferate pentru cod tipic de aplicație în timp ce render functions sunt potrivite pentru scenarii dinamice/de bibliotecă — te lasă să alegi instrumentul potrivit fără a forța o singură abordare peste tot.
