Vue3 Fundamentals ยท Modern Vue (3.5 / 3.6)

How the compiler optimises templates

Compiler optimisations

How the compiler optimises templates

A template is not HTML. Vue's compiler reads it at build time and turns it into a render function, and it uses that head start to do work the runtime would otherwise repeat on every render.

First it hoists what never changes. A subtree with no bindings is lifted out of the render function into a constant, so it is created once and reused instead of rebuilt each time. A static element that wraps dynamic children is marked as such, and its static parts are hoisted while only the dynamic parts are tracked.

Then it flattens the tree. The compiler collects the dynamic nodes into a flat list and tags each with a patch flag โ€” a number saying what can change, such as text or a class. When the component updates, Vue walks that short list and patches only the flagged nodes, instead of diffing the whole template.

It also caches inline event handlers, so a handler written in the template is created once rather than on every render.

You can watch it happen. The compiler's output is plain JavaScript, and the Vue SFC playground shows the render function beside your template. The optimisations are automatic; understanding them explains why a template with fewer dynamic parts has less work to do.

You are about to answer a short quiz on compiler optimisations.

  1. Vue compiles templates at build time into a render function.
  2. A subtree with no bindings is lifted out of the render function into a ___.
  3. A patch flag records what kind of thing can change in a dynamic node.
  4. The compiler collects dynamic nodes into a flat list so an update patches only the ___ nodes.
  5. The compiler caches inline event handlers so they are not recreated on every render.
  6. These optimisations require you to write special template syntax by hand.