Why You Should Avoid Vue.js DOM Templates

Anthony Gore
Nov 13, 2017 · 4 min read
Image for post
Image for post

DOM as a template

The el option is used to mount a Vue instance to an element in the DOM. If no template or render option is present, Vue will use any existing content within the mounting element as the template.

  • Syntax clashes with templating engines
  • Incompatibility with server-side rendering
  • Runtime template compilation is required

Markup != DOM

Let’s make a distinction between markup and the DOM. Markup is the HTML you write. The browser will then parse that and turn it into the DOM.

Clash with templating engines

If you’re using Vue.js in conjunction with a templating engine, any common syntax can be problematic.

Server-side rendering

You quite simply can’t use a DOM template if you want to server-side render your Vue app, as the HTML document is not an input of the SSR process.

Avoiding DOM templates

How can you architect a Vue.js app without a DOM template, or at least a small one?

1. Abstract markup to components

Your root instance can hold some state, but generally, you want any presentational logic and markup to be abstracted to components so it’s out of your DOM template.

x-templates

With x-templates, your template is still defined in the page, but within a script tag, and will, therefore, avoid processing by the DOM parser. The script tag is marked with text/x-template and referenced by an id in your component definition.

2. Mount to an empty node with a render function

Abstracting markup into components hits a wall when you realize you still need to declare your root-level component in the DOM template.

Summary

  • DOM templates are problematic as the DOM parser can mess with your markup. There’s also a potential for clashes with templating engines and incompatibility with server-side rendering.
  • To minimize your DOM template, abstract your markup into components.
  • To completely eliminate your DOM template you’ll need to mount your root-level component with a render function.

Vue.js Developers

Helping web professionals up their skill and knowledge of…

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store