July 08, 2016

How to Build a To-Do App in Vue.js - Part 1

by Lamin Sanneh

How to Build a To-Do App in Vue.js - Part 1

With web applications becoming more sophisticated, the popularity of JavaScript frameworks has been on the rise. With this increased fame, there are several capable frameworks out there to choose from. Some of the most popular choices are AngularJS, Ember.js and Vue.js. All these frameworks are capable of building large and modern web applications.

In this two-part article, we will be covering one of the above, which is Vue.js. We will build a Todo App. The main reason being that Vue.js takes a different approach to development. It has a lot of powerful features to match any of the above. When starting out with Vue.js you are only exposed to simple APIs on the surface. This makes it easy to get started but you could dig underneath and bring forth that power when needed.

In the first part of the Todo Application, we will cover how to setup Vue.js, setup a simple component. We will also touch on how to supply data to templates from a component class, loop over data in the templates and more.

In the second part, we will see how to handle events coming in from the template which will allow us to create more todos, edit them and eventually delete them.

Vue.js is currently at version 1 as of the time of this article with version 2 being still in preview. Beta should soon be out according to the Vue.js Blog. Let this not stop you from trying out the current version though as the API won't change much as mentioned by their blog post.

Install and setup Vue.js

With that out of the way, let us now setup our environment so we can get up and running with our Todo App. You will first need to have node.js and npm installed. After that, you must install vue-cli using the following command.

npm install - g vue - cli

vue-cli is a commandline tool which makes it easy to develop an application using Vue.js.

There are many templates to bootstrap a new Vue.js application using the vue-cli. We will use a popular one called webpack. This template scaffold outputs ES2015/ES6 JavaScript, the latest stable version of JavaScript. To create a new project, go to any folder and setup a new application using:

vue init webpack vuetodo

You may get asked a few questions on the way. Just keep pressing enter to carry on with the defaults.

Go inside the new directory using

cd vuetodo

Install the packages required by the application using

npm install

Finally, start the Vue.js development server using

npm run dev

This starts the server and watches your project folders for any file changes. It automatically refreshes the browser to reflect any detected changes. This is a term called hot module replacement. Speaking of the browser, visit the URL http://localhost:8080. You should see a brand new Vue.js application.

We will be using Twitter Bootstrap to help style our application. So copy the contents of the URL https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css from Bootstrap CDN and store it in static/css/bootstrap.css. Create another CSS file in static/css/style.css. Lastly, include these as CSS links inside of the main HTML file index.html like so.

<meta charset="utf-8" />

<link title="no title" href="/static/css/bootstrap.css" 
   rel="stylesheet" media="screen" />
<link title="no title" href="/static/css/style.css" 
   rel="stylesheet" media="screen" />

Our Vue.js Todo App Components Structure

Our Todo Application will comprise many components. A component helps us group pieces of functionality and visual representations into one “box”. For example, we can have a component for a list of contact details. The list itself could be a component. Since components can contain other sub-components, each contact detail itself could be a component.

Every Vue.js App needs to have a top-level component. In our Todo Application, we will have a main component for the skeleton of our application. Nested in the main component is a TodoList component – this component will contain a list of Todo components nested inside of it. To give you a visual understanding of the structure, have a look at the tree below.

MainComponent > TodoList > Todo

Main App Component

Now that we know more about the structure of our application, let us dig in and start building it. We will begin with the main top-level component. Most of our code will be in the src folder of our project. A main component was already created for us in src/App.vue. This will contain any sub-components which we will create.

Creating a Component

As part of the new application, there exists a component created for us in src/components/Hello.vue. Delete the file as we won't need it. Instead, we will create our own component called TodoList.vue inside of the components folder.

Inside of the new file, TodoList.vue, put in the following content.

Total Todo Count 
< span class = "badge" > 3 < /span> 
   < ul class = "list-group" >
    < li > Todo 1 < /li> 
    < li > Todo 2 < /li> 
    < li > Todo 3 < /li>
< /ul> 

< script type = "text/javascript" > // <![CDATA[
    export default {

    }
    // ]]></script>

What we’ve done here is create a component class and provide a template. A component file has three parts, a template area, a component class, and a styles area.

The template area is the visual part of a component. The class handles behavior and events and stores data which the template can access. The style part is for augmenting the presentation of the template.

For now, we will only have a template and a class part in the above component.

Protect your Vue App with Jscrambler

Importing Components

Next, let us make sure we can use the new component by importing it in our main component. So inside of App.vue, add the following line at the top of the script section

import TodoList from './components/TodoList'

Remove the line

import Hello from './components/Hello'

Also, remove the reference to the Hello component from the components property. Add a reference to the TodoList component we just imported. So it will look like this

components: {
    TodoList
}

Using a component

Now that we have a basic component setup, let's make use of it. Change the template of the main component src/App.vue to look like this.

<div class="container" id="app">
    <div class="page-header">
        <h1>Vue.js Todo App</h1>
    </div>

    <todo-list></todo-list>
</div>

To use a component, you need to invoke it like an HTML element as we’ve done above. You must separate words with dashes like below instead of camel case.

<todo-list></todo-list>

Component Data

Since our main component template will need to show a list of Todos, let's supply some data to it.

A single Todo has two properties named title and done. The title is the name of the Todo and done will represent whether the task is completed or not. Components provide data to their accompanying template through a data function. This function should return an object with the properties intended for the template. In our App Component, add a function returning an object with two properties like below.

export default {
    components: {
        TodoList
    },
    data() {
        return {
            newTodoText: '',
            todos: [{
                title: 'Todo 1',
                done: false
            }, {
                title: 'Todo 2',
                done: false
            }, {
                title: 'Todo 3',
                done: false
            }, {
                title: 'Todo 4',
                done: false
            }]
        };
    }

Note that we have two properties. The Todos property holds the list of todos. The newTodoText holds the text for creating a new todo.

Loops and Properties

Component Properties

We know that a component class can pass data to its template. Data can also be passed into a component when using it from a template. We have data in our main App.vue component class. Let's pass that down to the TodoList component. Change the main App.vue template to look like this:

<div class="container" id="app">
    <div class="page-header">
        <h1>Vue.js Todo App</h1>
    </div>

    <todo-list v-bind:todos="todos"></todo-list>
</div>

Notice this line

<todo-list v-bind:todos="todos"></todo-list>

We have passed the list of Todos down to the TodoList component. It will be available in that component through the name todos. This is because of the binding syntax used above.

It isn’t enough to just pass data down. We have to modify the TodoList component class. It has to declare what properties it will accept when using it. Modify the TodoList component class by adding a property to it like so.

export default {
    props: ['todos']

Looping Over Data

So now our TodoList component has revealed which properties it will accept. Inside the TodoList template, let's loop over the list of Todos like this and also show the length of the todos array

Total Todo Count <span class = "badge"> {{ todos.length }} </span>
<ul class = "list-group">
    <li> {{ todo.title }} </li>
</ul>

Now that we can loop over our todos using a TodoList component, let us end the part 1 here and, in the next part, we will go in-depth into events, methods, creating, editing and deleting todos.

If you're building Vue applications with sensitive logic, be sure to protect them against code theft and reverse-engineering by following our guide.