30 Days of Vue

Single File Components


This post is part of the series 30 Days of Vue.

In this series, we're starting from the very basics and walk through everything you need to know to get started with Vue. If you've ever wanted to learn Vue, this is the place to start!

Single File Components

Today, we'll discuss one of Vue's most useful features in helping build large scale Vue applications - Single File Components.

We've made it through 16 days already! Pat yourself on the back... but not for too long... there is still a lot more.

From what we've seen in the past few articles, we now have a good picture of how the Vue.component({}) constructor can be used to define global components and how we’re able to instead locally register components in the components property of a parent instance.

With either Vue.component({}) or components assigned to constant variables, we had to write our component templates using ES6’s template literals to obtain a presentable multiline format.

Vue.component('hello-world', {
  template: `
     <h1>Hello World</h1>
     <p>This is the Hello World component</p>

We’ve also taken a quick look at alternate template definitions like inline-template's and x-template's but have come to understand that both of these approaches are not recommended to creating the markup of components.

Template strings do a good job for small to medium sized projects. However, as an application grows, having no syntax highlighting and the entire markup of a component kept within back-ticks (or strings) makes the template of components hard to read. In addition, the components we’ve defined thus far don’t allow us to isolate the unique CSS within them. This is where Vue’s Single File Components can be used to help reduce this disorganization.

Single File Components

Single File Components allow us to define the HTML/CSS and JS of a component all within a single .vue file.

A single-file component is composed of three parts:

  • The <template> section which contains the component’s markup in plain HTML.
  • The <script> section which contains all the JS logic within that component.
  • The <style> section which contains all the component styles.

Here’s an example of a single-file component given the name of HelloWorld:

  <div class="hello-world">
    <h2>{{ getGreeting }}</h2>
    <p>This is the Hello World component.</p