VueJS: Single File Components

in VueJS Basics

When you're defining new components in VueJS you can use the method Vue.component like we've used in a previous tutorial about Vue.

<script>
    Vue.component('todo-item', {
        props: ['todo'],
        template: '<li>{{ todo.task }}</li>'
    })

    var app = new Vue({
        el: '#app',
        data: {
            todos: [
                { task: 'Learn JavaScript'},
                { task: 'Learn VueJS'},
                { task: 'Build awesome stuff'}
            ]
        }
    })
</script>

This has created a Vue component of todo-item the problem with this are:

  • Organising your components in the folder structure can be difficult
  • Template don't have any syntax highlights which can make HTML changes difficult
  • CSS needs to be processed outside of scope. Which makes CSS maintenance in the long run difficult
  • Restricts the use of preprocessor build tools such as Babel

Single file components solve all the above problems by providing you with one file to add your HTML, CSS and Vue object JavaScript.

To convert this to a single file component we need to use the file extension of .vue, so let's create a todo-component.vue and use Webpack to convert this to JavaScript and CSS.

The single file component can have a template tag for the HTML, a style tag for the CSS and a script tag for the Vue Javascript.

<template>
    <li>{{ todo.task }}</li>
</template>

<style>
    li
    {
        font-size: 125%;;
    }
</style>

<script>
    export default
    {
        props: ['todo'],
    }
</script>

As you can see the logic for the todo list component is now all contained inside this todo-component.vue file but the logic is separated into, HTML, CSS and JavaScript all within this file.

Module Builds With JavaScript

Vue components takes advantage of module builds in Javascript, which means we need to use additional tools within our Javascript development.

  • NPM (Node Package Manager) - Third party package manager for Javascript
  • Babels ES2015
  • Webpack - Module build converts to static Javascript and CSS files.

Learn more about webpack watch the video below.

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To Newsletter

Get weekly updates to your email