Tutorial

Build a To-Do App with Vue.js 2

Draft updated on Invalid Date
Default avatar

By Jeremy Kithome

Build a To-Do App with Vue.js 2

This tutorial is out of date and no longer maintained.

Introduction

Vue is a simple and minimal progressive JavaScript framework that can be used to build powerful web applications incrementally.

Vue is a lightweight alternative to other JavaScript frameworks like AngularJS. With an intermediate understanding of HTML, CSS, and JS, you should be ready to get up and running with Vue.

In this article, we will be building a to-do application with Vue while highlighting the bundle of awesomeness that it has to offer.

Let’s get started!

Prerequisites

We’ll need the Vue CLI to get started. The CLI provides a means of rapidly scaffolding Single Page Applications and in no time you will have an app running with hot-reload, lint-on-save, and production-ready builds.

Vue CLI offers a zero-configuration development tool for jumpstarting your Vue apps and component.

A lot of the decisions you have to make regarding how your app scales in the future are taken care of. The Vue CLI comes with an array of templates that provide a self-sufficient, out-of-the-box ready to use package. The currently available templates are:

  • webpack - A full-featured Webpack + Vue-loader setup with hot reload, linting, testing, and CSS extraction.
  • webpack-simple - A simple Webpack + Vue-loader setup for quick prototyping.
  • browserify - A full-featured Browserify + vueify setup with hot-reload, linting & unit testing.
  • browserify-simple - A simple Browserify + vueify setup for quick prototyping.
  • simple - The simplest possible Vue setup in a single HTML file

Simply put, the Vue CLI is the fastest way to get your apps up and running.

  1. # install vue-cli
  2. npm install --global vue-cli

In this tutorial, we will be focusing on the use of single file components instead of instances. We’ll also touch on how to use parent and child components and data exchange between them. Vue’s learning curve is especially gentle when you use single-file components. Additionally, they allow you to place everything regarding a component in one place. When you begin working on large applications, the ability to write reusable components will be a lifesaver.

Creating A Vue 2 Application

Next, we’ll set up our Vue app with the CLI.

  1. # create a new project using the "webpack" template
  2. vue init webpack todo-app

You will be prompted to enter a project name, description, author, and Vue build. We will not install Vue-router for our app. You will also be required to enable linting and testing options or the app. You can follow my example below.

Once we have initialized our app, we will need to install the required dependencies.

  1. # install dependencies and go!
  2. cd todo-app
  3. npm install

To serve the app, run:

  1. npm run dev

This will immediately open your browser and direct you to http://localhost:8080. The page will look as follows.

To style our application we will use Semantic. Semantic is a development framework that helps create beautiful, responsive layouts using human-friendly HTML. We will also use Sweetalert to prompt users to confirm actions. Sweetalert is a library that provides beautiful alternatives to the default JavaScript alert. Add the minified JavaScript and CSS scripts and links to your index.html file found at the root of your folder structure.

<!-- ./index.html -->
<head>
  <meta charset="utf-8">
  <title>todo-app</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.7/semantic.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.7/semantic.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
</head>

Component structure

Every Vue app, needs to have a top-level component that serves as the framework for the entire application. For our application, we will have a main component, and nested within shall be a TodoList component. Within this, there will be Todo sub-components.

Main App Component

Let’s dive into building our application. First, we’ll start with the main top-level component. The Vue CLI already generates a main component that can be found in src/App.vue. We will build out the other necessary components.

Creating a Component

The Vue CLI creates a component Hello during setup that can be found in src/components/Hello.vue. We will create our own component called TodoList.vue and won’t be needing this anymore.

Inside of the new TodoList.vue file, write the following.

<template>
  <div>
  <ul>
    <li> Todo A </li>
    <li> Todo B </li>
    <li> Todo C </li>
  </ul>
  </div>
</template>

<script type="text/javascript">
  export default {
  };
</script>

<style>
</style>

A component file consists of three parts; template, component class, and styles sections.

The template area is the visual part of a component. Behaviour, events, and data storage for the template are handled by the class. The style section serves to further improve the appearance of the template.

Importing Components

To utilize the component we just created, we need to import it into our main component. Inside of src/App.vue make the following changes just above the script section and below the template closing tag.

// add this line
import TodoList from './components/TodoList'
// remove this line
import Hello from './components/Hello'

We will also need to reference the TodoList component in the components property and delete the previous reference to Hello component. After the changes, our script should look like this.

<script>
import TodoList from './components/TodoList';

export default {
  components: {
    // Add a reference to the TodoList component in the components property
    TodoList,
  },
};
</script>

To render the component, we invoke it like an HTML element. Component words are separated with dashes like below instead of camel case.

<template>
  <div>
    // Render the TodoList component
    // TodoList becomes
    <todo-list></todo-list>
  </div>
</template>

When we have saved our changes our rudimentary app should look like this.

Adding Component Data

We will need to supply data to the main component that will be used to display the list of todos. Our todos will have three properties; The title, project, and done (to indicate if the todo is complete or not). Components provide data to their respective templates using a data function. This function returns an object with the properties intended for the template. Let’s add some data to our component.

export default {
  name: 'app',
  components: {
    TodoList,
  },
  // data function provides data to the template
  data() {
    return {
      todos: [{
        title: 'Todo A',
        project: 'Project A',
        done: false,
      }, {
        title: 'Todo B',
        project: 'Project B',
        done: true,
      }, {
        title: 'Todo C',
        project: 'Project C',
        done: false,
      }, {
        title: 'Todo D',
        project: 'Project D',
        done: false,
      }],
    };
  },
};

We will need to pass data from the main component to the TodoList component. For this, we will use the v-bind directive. The directive takes an argument which is indicated by a colon after the directive name. Our argument will be todos which tells the v-bind directive to bind the element’s todos attribute to the value of the expression todos.

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

The todos will now be available in the TodoList component as todos. We will have to modify our TodoList component to access this data. The TodoList component has to declare the properties it will accept when using it. We do this by adding a property to the component class.

export default {
    props: ['todos'],
}

Looping and Rendering Data

Inside our TodoList template let’s loop over the list of todos and also show the number of completed and uncompleted tasks. To render a list of items, we use the v-for directive. The syntax for doing this is represented as v-for="item in items" where items are the array with our data and item is a representation of the array element being iterated on.

<template>
  <div>
    // JavaScript expressions in Vue are enclosed in double curly brackets.
    <p>Completed Tasks: {{todos.filter(todo => {return todo.done === true}).length}}</p>
    <p>Pending Tasks: {{todos.filter(todo => {return todo.done === false}).length}}</p>
    <div class='ui centered card' v-for="todo in todos">
      <div class='content'>
        <div class='header'>
          {{ todo.title }}
        </div>
        <div class='meta'>
          {{ todo.project }}
        </div>
        <div class='extra content'>
          <span class='right floated edit icon'>
            <i class='edit icon'></i>
          </span>
        </div>
      </div>
      <div class='ui bottom attached green basic button' v-show="todo.done">
        Completed
      </div>
      <div class='ui bottom attached red basic button' v-show="!todo.done">
        Complete
      </div>
  </div>
</template>

<script type="text/javascript">
  export default {
    props: ['todos'],
  };
</script>

Editing a Todo

Let’s extract the todo template into it’s own component for cleaner code. Create a new component file Todo.vue in src/components and transfer the todo template. Our file should now look like this:

<template>
  <div class='ui centered card'>
    <div class='content'>
        <div class='header'>
            {{ todo.title }}
        </div>
        <div class='meta'>
            {{ todo.project }}
        </div>
        <div class='extra content'>
            <span class='right floated edit icon'>
            <i class='edit icon'></i>
          </span>
        </div>
    </div>
    <div class='ui bottom attached green basic button' v-show="todo.done">
        Completed
    </div>
    <div class='ui bottom attached red basic button' v-show="!todo.done">
        Complete
    </div>
</div>
</template>

<script type="text/javascript">
  export default {
    props: ['todo'],
  };
</script>

In the TodoList component refactor the code to render the Todo component. We will also need to change the way our todos are passed to the Todo component. We can use the v-for attribute on any components we create just like we would in any other element. The syntax will be like this: <my-component v-for="item in items" :key="item.id"></my-component>.

Note that from 2.2.0 and above, a key is required when using v-for with components.

An important thing to note is that this does not automatically pass the data to the component since components have their own isolated scopes. To pass the data, we have to use props.

<my-component v-for="(item, index) in items" v-bind:item="item" v-bind:index="index">
</my-component>

Our refactored TodoList component template:

<template>
  <div>
    <p>Completed Tasks: {{todos.filter(todo => {return todo.done === true}).length}}</p>
    <p>Pending Tasks: {{todos.filter(todo => {return todo.done === false}).length}}</p>
    // we are now passing the data to the todo component to render the todo list
    <todo v-for="todo in todos" v-bind:todo="todo"></todo>
  </div>
</template>

<script type = "text/javascript" >

import Todo from './Todo';

export default {
  props: ['todos'],
  components: {
    Todo,
  },
};
</script>

Let’s add a property to the Todo component class called isEditing. This will be used to determine whether the Todo is in edit mode or not. We will have an event handler on the Edit span in the template. This will trigger the showForm method when it gets clicked. This will set the isEditing property to true. Before we take a look at that, we will add a form and set conditionals to show the todo or the edit form depending on whether isEditing property is true or false. Our template should now look like this.

<template>
  <div class='ui centered card'>
    // Todo shown when we are not in editing mode.
    <div class="content" v-show="!isEditing">
      <div class='header'>
          {{ todo.title }}
      </div>
      <div class='meta'>
          {{ todo.project }}
      </div>
      <div class='extra content'>
          <span class='right floated edit icon' v-on:click="showForm">
          <i class='edit icon'></i>
        </span>
      </div>
    </div>
    // form is visible when we are in editing mode
    <div class="content" v-show="isEditing">
      <div class='ui form'>
        <div class='field'>
          <label>Title</label>
          <input type='text' v-model="todo.title" />
        </div>
        <div class='field'>
          <label>Project</label>
          <input type='text' v-model="todo.project" />
        </div>
        <div class='ui two button attached buttons'>
          <button class='ui basic blue button' v-on:click="hideForm">
            Close X
          </button>
        </div>
      </div>
    </div>
    <div class='ui bottom attached green basic button' v-show="!isEditing &&todo.done" disabled>
        Completed
    </div>
    <div class='ui bottom attached red basic button' v-show="!isEditing && !todo.done">
        Pending
    </div>
  </div>
</template>

In addition to the showForm method we will need to add a hideForm method to close the form when the cancel button is clicked. Let’s see what our script now looks like.

<script>
export default {
  props: ['todo'],
  data() {
    return {
      isEditing: false,
    };
  },
  methods: {
    showForm() {
      this.isEditing = true;
    },
    hideForm() {
      this.isEditing = false;
    },
  },
};
</script>

Since we have bound the form values to the todo values, editing the values will immediately edit the todo. Once done, we’ll press the close button to see the updated todo.

Deleting a Todo

Let’s begin by adding an icon to delete a Todo just below the edit icon.

<template>
  <span class='right floated edit icon' v-on:click="showForm">
    <i class='edit icon'></i>
  </span>
  /* add the trash icon in below the edit icon in the template */
  <span class='right floated trash icon' v-on:click="deleteTodo(todo)">
    <i class='trash icon'></i>
  </span>
</template>

Next, we’ll add a method to the component class to handle the icon click. This method will emit an event delete-todo to the parent TodoList Component and pass the current Todo to delete. We will add an event listener to the delete icon.

<span class='right floated trash icon' v-on:click="deleteTodo(todo)">
// Todo component
methods: {
    deleteTodo(todo) {
      this.$emit('delete-todo', todo);
    },
  },

The parent component (TodoList) will need an event handler to handle the delete. Let’s define it.

// TodoList component
methods: {
    deleteTodo(todo) {
      const todoIndex = this.todos.indexOf(todo);
      this.todos.splice(todoIndex, 1);
    },
  },

The deleteTodo method will be passed to the Todo component as follows.

// TodoList template
<todo v-on:delete-todo="deleteTodo" v-for="todo in todos" v-bind:todo="todo"></todo>\

Once we click on the delete icon, an event will be emitted and propagated to the parent component which will then delete it.

Adding A New Todo

To create a new todo, we’ll start by creating a new component CreateTodo in src/components. This will display a button with a plus sign that will turn into a form when clicked. It should look something like this.

<template>
  <div class='ui basic content center aligned segment'>
    <button class='ui basic button icon' v-on:click="openForm" v-show="!isCreating">
      <i class='plus icon'></i>
    </button>
    <div class='ui centered card' v-show="isCreating">
      <div class='content'>
        <div class='ui form'>
          <div class='field'>
            <label>Title</label>
            <input v-model="titleText" type='text' ref='title' defaultValue="" />
          </div>
          <div class='field'>
            <label>Project</label>
            <input type='text' ref='project' defaultValue="" />
          </div>
          <div class='ui two button attached buttons'>
            <button class='ui basic blue button' v-on:click="sendForm()">
              Create
            </button>
            <button class='ui basic red button' v-on:click="closeForm">
              Cancel
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      titleText: '',
      projectText: '',
      isCreating: false,
    };
  },
  methods: {
    openForm() {
      this.isCreating = true;
    },
    closeForm() {
      this.isCreating = false;
    },
    sendForm() {
      if (this.titleText.length > 0 && this.projectText.length > 0) {
        const title = this.titleText;
        const project = this.projectText;
        this.$emit('create-todo', {
          title,
          project,
          done: false,
        });
        this.newTodoText = '';
      }
      this.isCreating = false;
    },
  },
};
</script>

After creating the new component, we import it and add it to the components property in the component class.

// Main Component App.vue
  components: {
    TodoList,
    CreateTodo,
  },

We’ll also add a method for creating new todos.

// App.vue
  methods: {
    addTodo(title) {
      this.todos.push({
        title,
        done: false,
      });
    },
  },

The CreateTodo component will be invoked in the App.vue template as follows:

<create-todo v-on:add-todo="addTodo">

Completing A Todo

Finally, we’ll add a method completeTodo to the Todo component that emits an event complete-todo to the parent component when the pending button is clicked and sets the done status of the todo to true.

// Todo component
methods: {
      completeTodo(todo) {
        this.$emit('complete-todo', todo);
      },
}

An event handler will be added to the TodoList component to process the event.

methods: {
    completeTodo(todo) {
      const todoIndex = this.todos.indexOf(todo);
      this.todos[todoIndex].done = true;
    },
  },

To pass the TodoList method to the Todo component we will add it to the Todo component invocation.

<todo v-on:delete-todo="deleteTodo" v-on:complete-todo="completeTodo" v-for="todo in todos" :todo.sync="todo"></todo>

Conclusion

We have learned how to initialize a Vue app using the Vue CLI. In addition, we learned about component structure, adding data to components, event listeners, and event handlers. We saw how to create a todo, edit it and delete it. There is a lot more to learn. We used static data in our main component. The next step is to retrieve the data from a server and update it accordingly. We are now prepared to create an interactive Vue application. Try something else on your own and see how it goes. Cheers!

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Jeremy Kithome

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel