Vue Template

Posted on  by admin

There are numerous ways to define templates in Vue, but many of them don't work so well in production.

The docs even recommend avoiding some of them. Here's 3 ways to define templates for Vue components that work well with server-side rendering:. You can define a template in vanilla JavaScript as a string literal or template literal.

This approach means a component's HTML and JavaScript stay in the same file, which is generally considered a positive. The downside is that you don't get HTML syntax highlighting. You can use this approach but use a function to load the string.

This splits HTML and JavaScript into separate files to get better syntax highlighting and separation of concerns. Another approach that is similar to string templates is inline templates.

More Vue Tutorials

String Templates

Instead of defining an HTML template for every component, you define all your component HTML in one top-level template.

This is similar to slots. The advantage of this approach is you can define all your app's HTML in one template, but still break up business logic into separate components. Single file components give you the best of both worlds between putting your HTML template in a separate file and putting your HTML template as a string literal.

Like string literals, everything about a component is in one place. Like separate HTML files, you can get decent syntax highlighting. The tradeoff is that single file components are typically declared in a separate .vue file with its own special syntax.

Single File Components

Below is an example of .vue syntax. Depending on your IDE, you may need to install an additional package for .vue file syntax highlighting.

So in order to compile your component, you need a build step.

There are numerous tools that can do this for you, like the Vueify transform for Browserify and vue-loader for Webpack.

Under the hood, both of these tools use vue-template-compiler. Here's an example of using vue-template-compiler directly to compile Vue syntax into a component:.

Vue School has some of our favorite Vue video courses.

Inline Templates

Their Vue.js Master Class walks you through building a real world application, and does a great job of teaching you how to integrate Vue with Firebase.

In the case of boolean attributes, where their mere existence implies true, v-bind works a little differently. In this example:

If isButtonDisabled has the value of null, undefined, or false, the disabled attribute will not even be included in the rendered