Vue.js Tutorial for beginners

Vue.js Tutorial for beginners

In this tutorial, you are going to learn the basics of Vue.js. While we learn, we are going to build a Todo app that will help us to put in practice what we learn.

In this tutorial, you are going to learn the basics of Vue.js. While we learn, we are going to build a Todo app that will help us to put in practice what we learn.

A good way to learn a new framework, It’s by doing a Todo app. It’s an excellent way to compare framework features. It’s quick to implement and easy to understand. However, don’t be fooled by the simplicity, we are going to take it to the next level. We are going to explore advanced topics as well such as Vue Routing, Components, directives and many more!

Let’s first setup the dev environment, so we can focus on Vue! 🖖

1. Setup

We are going to start with essential HTML elements and CSS files and no JavaScript. You will learn how to add all the JavaScript functionality using Vue.js.

To get started quickly, clone the following repo and check out the start-here branch:

git clone https://github.com/amejiarosario/vue-todo-app.git
cd vue-todo-app
git checkout start-here

npm install
npm start

After running npm start, your browser should open on port [http://127.0.0.1:8080](http://127.0.0.1:8080 "http://127.0.0.1:8080") and show the todo app.

Try to interact with it. You cannot create a new Todos, nor can you delete them or edit them. We are going to implement that!

Open your favorite code editor (I recommend Code) on vue-todo-app directory.

1.1 Package.json

Take a look at the package.json dependencies:

"dependencies": {
  "todomvc-app-css": "2.1.2",
  "vue": "2.5.17",
  "vue-router": "3.0.1"
},
"devDependencies": {
  "live-server": "1.2.0"
}

We installed Vue and VueRouter dependencies. Also, we have the nice CSS library for Todo apps and live-server to serve and reload the page when we make changes. That’s all we would need for this tutorial.

1.2 Index.html

Open the index.html file. There we have the basic HTML structure for the Todo app that we are going to build upon:

  • Line 9: Loads the CSS from NPM module node_modules/todomvc-app-css/index.css.
  • Line 23: We have the ul and some hard-coded todo lists. We are going to change this in a bit.
  • Line 73: we have multiple script files that load Vue, VueRouter and an empty app.js.

Now, you know the basic structure where we are going to work on. Let’s get started with Vue! 🖖

2. Getting started with Vue

As you might know…

Vue.js is a reactive JavaScript framework to build UI components.
It’s reactive because the data and the DOM are linked. That means, that when data changes, it automatically updates the DOM. Let’s try that!

2.1 Vue Data & v-text

Go to app.js and type the following:

const todoApp = new Vue({
  el: '.todoapp',
  data: {
    title: 'Hello Vue!'
  }
});

The el is the element where Vue is going to be mounted. If you notice in the index.html that’s the section part. The data object is reactive. It keeps track of changes and re-render the DOM if needed. Go to the index page and change <h1>todos</h1> for <h1>{{ title }}</h1>. The rest remains the same:

<section class="todoapp">
  <header class="header">
    <h1>{{ title }}</h1>
    <input class="new-todo" placeholder="What needs to be done?" autofocus>
  </header>
  <!--  ...  -->

If you have npm start running you will see that the title changed!

You can also go to the console and change it todoApp.title = "Bucket List" and see that it updates the DOM.

Note: besides the curly braces you can also use v-text:

<h1 v-text="title"></h1>

Let’s do something useful and put an initial todo list:

const todoApp = new Vue({
  el: '.todoapp',
  data: {
    title: 'Todos',
    todos: [
      { text: 'Learn JavaScript ES6+ goodies', isDone: true },
      { text: 'Learn Vue', isDone: false },
      { text: 'Build something awesome', isDone: false },
    ],
  }
});

Now that we have the list we need to replace the <li> elements with each of the elements in the data.todos array.

Let’s do the CRUD (Create-Read-Update-Delete) of a Todo application.

review diff

2.2 READ: List rendering with v-for

As you can see everything starting with v- is defined by the Vue library.

We can iterate through elements using v-for as follows:

<li v-for="todo in todos">
  <div class="view">
    <input class="toggle" type="checkbox">
    <label>{{todo.text}}</label>
    <button class="destroy"></button>
  </div>
  <input class="edit" value="Rule the web">
</li>

You can remove the other <li> tag that was just a placeholder.

review diff

2.3 CREATE Todo and event directives

We are going to implement the create functionality. We have a textbox, and when we press enter, we would like to add whatever we typed to the list.

In Vue, we can listen to an event using v-on:EVENT_NAME. E.g.:

  • Line 9: Loads the CSS from NPM module node_modules/todomvc-app-css/index.css.
  • Line 23: We have the ul and some hard-coded todo lists. We are going to change this in a bit.
  • Line 73: we have multiple script files that load Vue, VueRouter and an empty app.js.

Protip: since v-on: is used a lot, there’s a shortcut @. E.g. Instead of v-on:keyup.enter it can be [@keyup.enter](mailto:@keyup.enter)`.

Let’s use the keyup.enter to create a todo:

<input class="new-todo" placeholder="What needs to be done?"
  v-on:keyup.enter="createTodo"
  autofocus>

On enter we are calling createTodo method, but it’s not defined yet. Let’s define it on app.js as follows:

methods: {
  createTodo(event) {
    const textbox = event.target;
    this.todos.push({ text: textbox.value, isDone: false });
    textbox.value = '';
  }
}

review diff

2.4 Applying classes dynamically & Vue v-bind

If you click the checkbox (or checkcirlcle) we would like the class completed to be applied to the element. We can accomplish this by using the v-bind directive.

v-bind can be applied to any HTML attribute such as class, title and so forth. Since v-bind is used a lot we can have a shortcut :, so instead of v-bind:class it becomes :class.

<li v-for="todo in todos" :class="{ completed: todo.isDone }">

Now if a Todo list is completed, it will become cross out. However, if we click on the checkbox, it doesn’t update the isDone property. Let’s fix that next.

review diff

2.5 Keep DOM and data in sync with Vue v-model

The todos have a property called isDone if it’s true we want the checkbox to be marked. That’s data -> DOM. We also want if we change the DOM (click the checkbox) we want to update the data (DOM -> data). This bi-directional communication is easy to do using v-model, it will keep it in sync for you!

<input class="toggle" type="checkbox" v-model="todo.isDone">

If you test the app now, you can see when you click the checkbox; also the text gets cross out. Yay!

You can also go to the console and verify that if you change the data directly, it will immediately update the HTML. Type the following in the browser console where you todo app is running:

todoApp.todos[2].isDone = true

You should see the update. Cool!

2.6 UPDATE todo list with a double-click

We want to double click on any list and that it automatically becomes a checkbox. We have some CSS magic to do that, the only thing we need to do is to apply the editing class.

<!-- List items should get the class `editing` when editing and `completed` when marked as completed -->
<li v-for="todo in todos" :class="{ completed: todo.isDone }">
  <div class="view">
    <input class="toggle" type="checkbox" v-model="todo.isDone">
    <label>{{todo.text}}</label>
    <button class="destroy"></button>
  </div>
  <input class="edit" value="Rule the web">
</li>

Similar to what we did with the completed class, we need to add a condition when we start editing.

Starting with the label, we want to start editing when we double-click on it. Vue provides v-on:dblclick or shorthand @dblclick:

<label @dblclick="startEditing(todo)">{{todo.text}}</label>

In the app.js we can define start editing as follows:

const todoApp = new Vue({
  el: '.todoapp',
  data: {
    title: 'Todos',
    todos: [
      { text: 'Learn JavaScript ES6+ goodies', isDone: true },
      { text: 'Learn Vue', isDone: false },
      { text: 'Build something awesome', isDone: false },
    ],
    editing: null,
  },
  methods: {
    createTodo(event) {
      const textbox = event.target;
      this.todos.push({ text: textbox.value, isDone: false });
      textbox.value = '';
    },
    startEditing(todo) {
      this.editing = todo;
    },
  }
});

We created a new variable editing in data. We just set whatever todo we are currently editing. We want only to edit one at a time, so this works perfectly. When you double-click the label, the startEditing function is called and set the editing variable to the current todo element.

Next, we need to apply the editing class:

<li v-for="todo in todos" :class="{ completed: todo.isDone, editing: todo === editing }">

When data.editing matches the todo , then we apply the CSS class. Try it out!

If you try it out, you will notice you can enter on edit mode, but there’s no way to exit from it (yet). Let’s fix that.

<input class="edit"
  @keyup.esc="cancelEditing"
  @keyup.enter="finishEditing"
  @blur="finishEditing"
  :value="todo.text">

First, we want the input textbox to have the value of the todo.text when we enter to the editing mode. We can accomplish this using :value="todo.text". Remember that colon : is a shorthand for v-bind.

Before, we implemented the startEditing function. Now, we need to complete the edit functionality with these two more methods:

  • Line 9: Loads the CSS from NPM module node_modules/todomvc-app-css/index.css.
  • Line 23: We have the ul and some hard-coded todo lists. We are going to change this in a bit.
  • Line 73: we have multiple script files that load Vue, VueRouter and an empty app.js.

Let’s go to the app.js and define these two functions.

finishEditing(event) {
  if (!this.editing) { return; }
  const textbox = event.target;
  this.editing.text = textbox.value;
  this.editing = null;
},
cancelEditing() {
  this.editing = null;
}

Cancel is pretty straightforward. It just set editing to null.

finishEditing will take the input current’s value (event.target.value) and copy over the todo element that is currently being edited. That’s it!

review diff

2.7 DELETE todo list on @click event

Finally, the last step to complete the CRUD operations is deleting. We are going to listen for click events on the destroy icon:

<button class="destroy" @click="destroyTodo(todo)"></button>

also, destroyTodo implementation is as follows:

destroyTodo(todo) {
  const index = this.todos.indexOf(todo);
  this.todos.splice(index, 1);
},

review diff

2.8 Trimming inputs

It’s always a good idea to trim user inputs, so any accidental whitespace doesn’t get in the way with textbox.value.trim().

review diff

2.9 Items left count with computed properties

Right now the item left count is always 0. We want the number of remaining tasks. We could do something like this:

<strong>{{ todos.filter(t => !t.isDone).length }}</strong> item(s) left</span>

That’s a little ugly to stick out all that logic into the template. That’s why Vue has the computed section!

computed: {
  activeTodos() {
    return this.todos.filter(t => !t.isDone);
  }
}

Now the template is cleaner:

	

<strong>{{ activeTodos.length }}</strong> item(s) left</span>

You might ask, why use a computed property when we can create a method instead?

Vue.js is a reactive JavaScript framework to build UI components.
Try completing other tasks and verify that the count gets updated.

review diff

2.10 Clearing completed tasks & conditional rendering with v-show

We want to show clear completed button only if there are any completed task. We can accomplish this with the v-show directive:

<button class="clear-completed" @click="clearCompleted" v-show="completedTodos.length">Clear completed</button>

The v-show will hide the element if the expression evaluates to false or 0.

One way to clearing out completed tasks is by assigning the activeTodos property to the todos:

clearCompleted() {
  this.todos = this.activeTodos;
}

Also, we have to add the computed property completedTodos that we use in the v-show

completedTodos() {
  return this.todos.filter(t => t.isDone);
}

review diff

3. Vue Conditional Rendering: v-show vs v-if

v-show and v-if looks very similar, but they work differently. v-if removes the element from the DOM and disable events, while v-show hides it with the CSS display: none;. So, v-if is more expensive than v-show.

Vue.js is a reactive JavaScript framework to build UI components.
We can hide the footer and central section if there’s no todo list.

<section class="main" v-if="todos.length">... </section>
<footer class="footer" v-if="todos.length">...</footer>

review diff

4. Local Storage

On every refresh, our list gets reset. This is useful for dev but not for users. Let’s persist our Todos in the local storage.

Vue.js is a reactive JavaScript framework to build UI components.
The way localStorage works is straightforward. It is global variable and has only 4 methods:

  • Line 9: Loads the CSS from NPM module node_modules/todomvc-app-css/index.css.
  • Line 23: We have the ul and some hard-coded todo lists. We are going to change this in a bit.
  • Line 73: we have multiple script files that load Vue, VueRouter and an empty app.js.

We are going to use getItem and setItem. First we need to define a storage key:

const LOCAL_STORAGE_KEY = 'todo-app-vue';

Then we replace data.todos to get items (if any) from the local storage:

data: {
  title: 'Todos',
  todos: JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) || [
    { text: 'Learn JavaScript ES6+ goodies', isDone: true },
    { text: 'Learn Vue', isDone: false },
    { text: 'Build something awesome', isDone: false },
  ],
  editing: null,
},

We have to use JSON.parse because everything gets stored as a string and we need to convert it to an object.

getItem will retrieve the saved todos from the localstorage. However, we are saying it yet. Let’s see how we can do that.

5. Vue Watchers

For saving, we are going to use the Vue watchers.

Vue.js is a reactive JavaScript framework to build UI components.

watch: {
  todos: {
    deep: true,
    handler(newValue) {
      localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(newValue));
    }
  }
},

This expression watches for changes in our todos data. Deep means that it recursively watches for changes in the values inside arrays and objects. If there’s a change, we save them to the local storage.

review diff

Once you change some todos, you will see they are stored in the local storage. You can access them using the browser’s dev tools:

The last part to implement is the routing! However, for that, we need to explain some more concepts and will do that in the next post.

In the next tutorial, we are going to switch gears a little bit and go deeper into Vue Components, Routing, and Local Storage. Stay tuned!

6. Summary: Vue cheatsheet

We learned a lot!

What are the differences between the various JavaScript frameworks? E.g. Vue.js, Angular.js, React.js

What are the differences? Do they each have specific use contexts?

What are the differences? Do they each have specific use contexts?

Ember.js vs Vue.js - Which is JavaScript Framework Works Better for You

Ember.js vs Vue.js - Which is JavaScript Framework Works Better for You

In this article we will discuss full details and comparison of both Ember.js and Vue.js

JavaScript was initially created to work for web applications. But today they have become the favorite of mobile app developers. Most of the developers prefer to work with frameworks based on JavaScript. It simplifies coding. You can use JavaScript with almost any framework.

The use of a particular framework will decide how easy and fast it is to create the app. So, you must choose the best one suited for the app that you are planning to build. You must make a wise choice so that you benefit in the end. Among the crowded market, two of the frameworks stand out. We will make a comparison between Ember.js and Vue.js.

Why Do You Select A Particular Framework?

Before we start comparing the two frameworks, we should understand the factors that lead to the choice of a framework. Each developer chooses a framework before he or she goes to work on an app. Let us see the reasons for the selection.

● The codes must be easy to understand and transparent.

● The framework should give the maximum power with the least amount of coding.

● The framework should provide a well laid out structure to work on.

● Does the framework support an in-built router or an external plug-in router?

● The framework should be able to transfer more data on a full page-load so that it becomes a single-page app. A single-page app is more beneficial for the application.

● In single page architectures if there is a need for users to share links to sub-screens within the interface, then the framework should have the capacity to route based on the URL.

● A tighter template option can help in enabling two-way binding.

● The framework should not conflict any third-party library.

● Testing the codes inside the framework should be easy.

● The framework should provide the HTTP client service for AJAX calls

● The documentation is essential. It should be complete and up-to-date.

● The framework should be compatible with the latest version of the browser.

● The framework has to fulfill the above conditions for easy construction of the app. You must ensure that the framework you choose meets the conditions.

Vue.js Explained

Developers are always looking at new frameworks to build their apps. The main requirements are speed and low cost. The framework should be easy to use by even new developers. You should be able to use it at low cost. Other considerations are about simple coding, proper documentation, etc.

Vue.js combines a lot of good when it comes to software language for web app development. The architecture of Vue.js is easy to put in use. The apps developed using Vue.js are easy to integrate with new apps.

Vue.js is a very lightweight framework. It makes it fast to download. It is also much faster than other frameworks. The single-file component nature of the framework is also beneficial. The size has made it very popular.

You can further decrease weight. With Vue.js you can separate the template-to-virtual DOM and compiler. You can only deploy the minified and zipped interpreter which is only 12 KB. You can compile the templates in your machine.

Another significant advantage of Vue.js is that it can integrate easily with existing applications created with JavaScript. It will make it easy for using this framework to make changes to applications already present.

Vue.js also integrates easily with other front-end libraries. You can plug in another library and make up for any deficiency in this framework. This feature makes this tool a versatile one.

Vue.js uses the method of rendering on the streaming-side server. You can render your component and get a readable stream. You can then send this to the HTTP server. It makes the server highly responsive. Your users will get the rendered content very quickly.

Vue.js is very SEO friendly. As the framework supports server-side rendering, the views are rendered directly on the server. The search engines list these.

But the most important thing for you is the ease with which you can learn Vue.js. The structure is elementary. Even new developers will find it easy to use it to build their apps. This framework helps in developing both small and large templates. It helps to save a lot of time.

You can go back and check your errors very easily. You can travel back and inspect all the states apart from testing your components. It is another important feature as far as any developer is concerned.

Vue.js also has very detailed documentation. It helps in writing your applications very quickly. You can build a web page or app with the basic knowledge of HTML or JavaScript.

● Vue.js has pure architecture. It helps in integration with other apps

● Vue.js is lightweight and fast. It can be made lighter by deploying only the interpreter

● You can separate the compiler and the template-to-virtual DOM.

● Due to smooth integration, you can use this to make changes to existing apps

● To make up for any shortfall, you can plug-in any library and makeup.

● As Vue.js uses streaming-side server rendering, your users can get quick responses.

● The server-side rendering also helps in being ranked higher by search engines.

● It has a simple structure. Easy to use for any new developer

● You can go back and check and correct your errors.

● You can check all the existing states.

● Detail documentation also helps build the web page or application very quickly.

Ember.js Decoded

Ember.js is an MVVM model framework. It is open-source software. This platform is mostly used for creating complex multi-page applications. It maintains up-to-date features without discarding any of the old features.

With this framework, you have to follow the architecture of the framework strictly. The JS framework is very tightly organized. It reduces the flexibility that other frameworks might offer.

There is a very refined and developed control system for its platforms and tools. You can integrate it with the new version with the tools provided. There is strict guidance about avoiding outdated APIs.

You can understand Ember’s APIs easily. They are also easy to work. You can make use of highly complex functionalities simply and straightforwardly.

The performance is better as similar jobs are processed together. It creates batches of similar bindings and DOM updates to improve the performance. It means that the browser needs to process them in one go. It will avoid recomputing for each task, wasting a lot of time.

You can write the codes in a simple manner and modules. You can use any of Ember’s APIs. It is possible due to the presence of Promises everywhere.

Ember comes with a well-written guide. The API is recorded in a useful manner. It is a front-end framework that is loaded. Ember has a router, pipeline, services, etc. of its own.

The basis for views, controllers, models, and framework is the Ember Object Model. All components come from the same objects. The framework is firm and steady. The reason is that all elements have similar jobs and characteristics.

Ember has made the general application, organization, and structure clear so that you don’t make any mistakes. You will have no chance to complicate the application unnecessarily. If you have to go out of the defined limits, you will have to force your way out.

The language used for templating in Embers is Handlebars. This language helps Embers to keep its logic out of view. The clean syntax of Handlebars makes it easy for you to read and understand the templates. Handlebar templates are faster to load.

Another advantage you gain from Handlebar is that you don’t have to update your template every time you add or remove data from the page. It will be done automatically by the language itself.

A community that is continually improving the framework supports Ember. They are updating the framework with the latest technology. They also make sure that backward compatibility is possible.

● Ember.js is an open-source MVVM model framework suitable for complex multiple-page applications.

● It offers both the latest and old features.

● It has a very tightly structured framework which doesn’t offer much flexibility

● A very refined control system helps you to integrate with new versions without any problem.

● There is strict guidance about avoiding outdated API versions.

● Ember’s APIs help you to use complex functionalities in a simple manner

● There is no recomputing for each task as the framework allows the browser to do similar functions together.

● Promises allow you to write modular and straightforward code using any API of Ember.js.

● Ember.js is a fully loaded, front-end framework.

● The framework is stable because all components have the same functionalities and properties.

● It has well-defined limitations which will prevent your complicating your application

● Handlebars, the language used by Ember.js allows you to read and understand templates easily. It also helps to load the templates faster.

● Handlebars will ensure to update the template every time you add or remove data.

● Ember.js has an active community that updates the framework regularly and facilitates backward compatibility.

A Comparison Between Ember.js And Vue.js

This article intends to compare the features of both frameworks. Let us see how the characteristics of these frameworks compare. It will help you to make use of the right framework for your web application.

When you need a modern engine for an old application, it is Vue.js which will help you. It combines the best properties of other frameworks. Vue.js is a developing framework. A ready-to-use library of interface elements does not exist. However, many third-party libraries can help you.

Ember.js offers you a well-organized and trustworthy framework. When the development team is big, this is the framework that suits best. It allows everyone to understand the written code and contribute to a common project. The technology will be up-to-date, and the platform will be stable.

Vue.js can help you use the syntax of different kinds. It helps in writing the codes with ease. It is also an SEO friendly framework. Ember is a fully loaded front-end framework and can help you develop the applications very fast. But it is not suitable for developing small projects.

It is not easy to say this is better than that. It will depend on what kind of project you have undertaken. Both have their pluses and minuses. The below table will help in a better comparison.

Final Thoughts

It is not easy to conclude as to which is better. It all depends on the application that you want to develop. Both frameworks are developing. Both are getting updates. Both the communities are working on the frameworks.

While Vue.js is more comfortable for writing codes, Ember is a full-stack framework allowing the development of apps very fast. It is suitable for big projects. It is too complicated to be used for smaller projects.

We hope you had a great time reading this article. If you’ve any questions or suggestions related to this blog, then feel free to ask them in the comment section. Thank You.!