How To Build Your First Vue.js Application

How To Build Your First Vue.js Application
Develop a stylish to-do list application in Vue.js with animations

Vue.js is a very interesting JavaScript framework for building user interfaces: Not only it is very light (20 KB min+gzip), but it also has a steeper learning curve than its competitors.

Purpose of This Article

I’m going to show you a complete example of Vue.js in action from scratch, trying to avoid complex constructs that may confuse the beginners of this framework. We will work with just a text editor(here I’m using Notepad++) and a browser (the latest version of whichever browser you use is fine).

We will develop an interactive to-do listwith animations when adding a to-do item, setting it as completed, and removing it. You can see the whole final result in my repository.

First Steps

Let’s define a sort of template for each example we will implement. Create a new HTML file and name it index.html. The most important things to do are:

  • Import Vue.js: <script src=”[https://unpkg.com/vue/dist/vue.js](https://unpkg.com/vue/dist/vue.js)"> </script>
  • Define and import a stylesheet: <link href=”style.css” rel=”stylesheet” />
  • Create a new JavaScript file, app.js, where we will code the Vue application and import it before the body end tag`
  • Define a simple page layout with a nav, header, and a main content div
  • Style the page a bit to make it look good — in my example, I styled it with a dark themeinspired by Google Keep

At a very early development stage, our application looks like this:

This is image title

As you can see, the layout is composed of:

  • A header with a title
  • An input box in which we will write a new to-do item, with a little + button to insert it into our list (of course, we will also enable pressing the Enter keyboard key to insert a new item)
  • A list of to-do items with a fixed width but a dynamic height to allow larger notes
  • A checkbox for each to-do item
  • A button to remove the item

Of course, at this moment the data you see is just Lorem Ipsum static data.

Considering only the HTML structure (you can see the stylesheet at this stage), the page is composed of these elements (complete page):

medium-article-vue-3.html

<div id="main-content">

  <ul>

    <li class="todo-item">
      <span class="todo-text">Lorem ipsum dolor sit amet</span>

      <label class="todo-check">
        <input type="checkbox" />
        <span class="checkmark"></span>
      </label>
    </li>

    <li class="todo-item">
      <span class="todo-text">Sed fringilla tellus nec finibus maximus. Duis venenatis risus purus. Duis magna odio, eleifend vitae dignissim gravida, semper volutpat nisl</span>

      <label class="todo-check">
        <input type="checkbox" />
        <span class="checkmark"></span>
      </label>
    </li>

    <li class="todo-item">
      <span class="todo-text completed">Ut nec erat non nulla ultricies condimentum</span>

      <label class="todo-check">
        <input type="checkbox" />
        <span class="checkmark"></span>
      </label>
    </li>

  </ul>

</div>

Vue.js

One may ask: Why do I need a JavaScript framework at this point?

In a real use case, you’ll probably grab the data from an API, and you won’t want to manually manipulate the DOM via jQuery or similar by adding, row by row, each <li>. If you do that, when you need to save all the changes in your application, you’ll have to iterate each list of properties, define an array with those elements, and call an update command to your API.

With a JavaScript framework like Vue.js, however, your presentation is always bound to your view model arrays. Thus, the procedure will be invisible to you, and you’ll have to write a lot less code.

Of course, you can can it manually, but, in my experience, it’s more error-prone because you have to care about some lower-level structures (such as getting the correct element, editing the correct property, etc.).

Also, it’s a lot more immediate to write your view model properties directly to your main page. In this example, we will write the text of each to-do item simply in this way: <.

A New Vue.js Application

A single to-do item is just composed of two properties:

  • Text, a string that represents the note text
  • IsDone, an auto-explicative Boolean

Let’s define a simple array with test data in our app.js file:

medium-article-vue-4.js

var testData = [
  { Text: "Lorem ipsum dolor sit amet", IsDone: false },
  { Text: "Sed fringilla tellus nec finibus maximus. Duis venenatis risus purus. Duis magna odio, eleifend vitae dignissim gravida, semper volutpat nisl", IsDone: false },
  { Text: "Ut nec erat non nulla ultricies condimentum", IsDone: true },
];

Then, define a new Vue application:

medium-article-vue-5.js

var todoListApp = new Vue({
  el: '#app-todolist',
  data: {
    todoItems: testData
  }
})

In the Vue object, we are currently setting:

  • el: a property with our DOM application container that should wrap all the dynamic parts of our website. If you see the whole HTML structure of this example, you see that I wrapped the content with the external div <div id=”app-todolist”>.
  • data: a property that should contain the model data that we want to bind. In this case, we set the previously defined testData array, but in a real case, you will grab that from an API or from a JSON file.

Binding Data

Now we just have to bind our Vue todoItems property to our index.html page. We remove all manually added <li> tags and substitute them with:

medium-article-vue-6.html

<ul>

  <li v-for="todo in todoItems" class="todo-item">

    <label class="todo-check">
      <input type="checkbox" v-model="todo.IsDone" v-on:click="move(todo)" />
      <span class="checkmark"></span>
    </label>

    <span class="todo-text" v-bind:class="{ completed: todo.IsDone }">{{ todo.Text }}</span>

    <a href="" onclick="return false;" title="Remove this item">x</a>

  </li>

</ul>

Things to note:

  • v-for: A Vue Js construct to declare a list of objects where each object will be rendered as a li element
  • v-bind:class=”{ completed: todo.IsDone }”: Here we are telling Vue to mark the class as completed if the Boolean property IsDone is true on the current to-do item (if the property value changes, Vue removes the class in real time)
  • {{ todo.Text }}: The Vue.Js syntax to print an element property (todo is the name of the iterator variable in v-for)
  • v-model=”todo.IsDone”: This command bindsthe property IsDone of the current to-do item to the checkbox value. If the property value is true, the checkbox is selected; otherwise, it is unselected.

Adding User Interaction

Now that we created some bindings between data (testData array) and the data representation (the webpage), it’s time to let the user interact with it.

We are going to add the possibility to add a new to-do item by clicking the + button or by pressing the Enter key on the keyboard.

First of all, let’s add to our Vue application in the JavaScript file an object that serves as a model for a new object. It needs to have the same properties as testData array and has to be added into the data property:

medium-article-vue-8.js

data: {
  todoItems: testData,
  newTodoText: ""
},

Then, we need to add a new method to our Vue application to be bound to the click event of our front-end button:

medium-article-vue-9.js

methods: {

  addTodo: function() {

    if (this.newTodoText.trim() == "")
      return;

    this.todoItems.push({ Text: this.newTodoText, IsDone: false});
    this.newTodoText = "";
    
  }
}

The method’s name is addTodo, and it firstly checks for an empty input (this part can be made far better — here is just a written as a placeholder). Then it creates a new object with the same data contained in the newTodo object of our Vue application.

Note that we access the Vue-application properties by referencing the application object directly — they aren’t in the scope of the method.

At the end of the method, we append the new object at the end of our to-do list array, and we clear the input.

The last thing to do is to bind the method to our front-end click event:

medium-article-vue-7.html

<div id="commands">
  <input type="text" placeholder="Write something..." v-model="newTodoText" v-on:keyup.enter="addTodo()" /> 
  <a href="" v-on:click="addTodo()" onclick="return false;" title="Add a new item">+</a>
</div>
  • v.model=”newTodoText” is used to bind user input to the Vue application newTodoText string property. This ensures that when the user writes something in the new to-do item text-box, the inserted text is assigned to our application variable
  • onclick=”return false;”: We add this to prevent the browser from reloading the page when we click the button (that is a simple a link)
  • v-on:click=”addTodo()” is the link between the click event and the application method we defined earlier
  • v-on:keyup.enter=”addTodo()” permits us to add a new item not by pressing the button but also by pressing the Enter key on the keyboard

Removing an Element

To let a user remove an element, we just add the method removeTodo to our methods property in the Vue application. In this case, the method takes the todo list item object we want to remove:

medium-article-vue-10.js

removeTodo: function(todo) {
  this.todoItems.splice(this.todoItems.indexOf(todo), 1);
}

Then, bind the method to the deletion button with v-on:click as we did earlier for the item-adding command:

medium-article-vue-11.js

<a href="" v-on:click="removeTodo(todo)" onclick="return false;" title="Remove this item">x</a>

Now our to-do list is really looking good — and it works perfectly. The last thing we need to please the eyes is to add some animations.

Animations

In Vue.js, it’s very easy to animate a list of items. The keyword to remember is <transition-group>.

The first thing to do is to replace our <ul> tag with a <transition-group> tag that will wrap the<li> definition. The two attributes to care about are:

  • tag=”ul” specifies how the transition group will be rendered (if you inspect the DOM after the page loads, you will see that the transition-group tag doesn’t exist but there is an ul instead)
  • name=”list-animation”: The name of the animation that has to applied on each list item (we will write it down in a second)

The second, very important thing, is to choose a key for each item. Otherwise, the animation won’t work. In this example, we will do it in a quick-and-dirty way(because this article is only a tutorial) by just defining a global-incremental integer that will increment on a new to-do list item.

medium-article-vue-12.js

var itemIndex = 0;

function GetFreeItemIndex() {
  itemIndex++;
  return itemIndex;
}

Each item will now have an Id, and we will use it as key for the animation:

medium-article-vue-13.html

<li v-for="todo in todoItems" v-bind:key="todo.Id" class="todo-item todo-item-animated">

  • v-bind:key=”todo.Id”: the binding of the item key
  • I added the todo-item-animated class to the li item to manage the object transitions

Finally, here is the CSS of the animations (to make an item fade out, fade in, and translate up):

medium-article-vue-13.css

.todo-item-animated {
  transition: all 0.5s;
}

.list-animation-enter, .list-animation-leave-to {
  opacity: 0;
  transform: translateY(30px);
}

.list-animation-leave-active {
  position: absolute;
}

Our to-do application is now completed:

Suggest:

Vue js Tutorial Zero to Hero || Brief Overview about Vue.js || Learn VueJS 2023 || JS Framework

Learn Vue.js from scratch 2018

Is Vue.js 3.0 Breaking Vue? Vue 3.0 Preview!

Vue.js Tutorial: Zero to Sixty

Learn Vue.js from Scratch - Full Course for Beginners

Create Shopping basket page With Vuejs and Nodejs