7 Ways To Define A Component Template in VueJS
There’s plenty of choice when it comes to defining component templates in Vue. By my count there are at least seven different ways:
- Template literal
- Render functions
- Single page components
And maybe more!
In this article we’ll go through examples of each and address the pros and cons so you know which one is the best to use in any particular situation.
Note: this article was originally posted here on the Vue.js Developers blog on 2017/03/24.
By default a template will be defined as a string in your JS file. I think we can all agree that templates in a string are quite incomprehensible. This method doesn’t have much going for it other than the wide browser support.
2. Template literals
This method isn’t perfect, though; I find that most IDEs still give you grief with syntax highlighting, and formatting the tabs, newlines etc can still be a pain.
With this method your template is defined inside a script tag in the index.html file. Th script tag is marked with
text/x-template and referenced by an id in your component definition.
I like that this method allows you to write your HTML in proper HTML markup, but the downside is that it separate the template from the rest of the component definition.
4. Inline Templates
By adding the
inline-template attribute to a component, you indicate to Vue that the inner content is its template, rather than treating it as distributed content (see slots).
5. Render functions
The most controversial template option in Vue is JSX. Some developers see JSX as ugly, unintuitive and as a betrayal to the Vue ethos.
JSX requires you to transpile first, as it is not readable by browsers. But, if you need to use render functions, JSX is surely a less abstract way of defining a template.
7. Single File Components
So long as you are comfortable with using a build tool in your setup, Single File Components are the king of template options. They bring the best of both worlds: allowing you to write markup while keeping all your component defintion in one file.
They require transpiling and some IDEs don’t support syntax highlighting for this file type, but are otherwise hard to beat.
You might argue there are even more template definition possibilities since you can use template pre-processors like Pug with SFCs!
Which is the best?
Of course there’s no one perfect way, and each should be judged on the use case you have. I think the best developers will be aware of all the possibilities and have each as a tool in their Vue.js toolbelt!
Get the latest Vue.js articles, tutorials and cool projects in your inbox with the Vue.js Developers Newsletter.