5 reasons developers are switching to Vue.js - Heart Internet Blog - Focusing on all aspects of the web

The Vue.js framework is quickly gaining in popularity, and although it won’t have the market share of other frameworks for a while, more and more companies are considering it for projects. So let’s dive into how it compares with other frameworks and some of the reasons why it might be your next framework. I’ve built a similar application using jQuery, React and Vue.js. You can see a sample of the working app built with Vue.js here.

Screenshot of the github repository for the Vue.js app

Installation

In a way, getting started with Vue.js is similar to getting started with a framework like jQuery and the original AngularJS (Angular 1). Although you can install the framework in a couple of ways, just like with jQuery, you can simply load up a script tag from either a CDN or a single script tag to get started.

<script src="https://cdn.jsdelivr.net/npm/vue"></script>

That’s all you need for most simple applications. Compare that with Angular’s quickstart, or even React’s installation process where you must depend on a complex terminal Command Line Interface (CLI) to get even simpler applications working. Simplicity matters when you either want to get simple things working without a lot of overhead or are just starting to learn the features of a framework or library.

What do you get with that script tag? You get a lot of powerful features like a built-in data-binding and templating engine. If you look at the simplest Vue.js example, this becomes obvious:

<div id="app">
     <p>{{ message }}</p>
</div>
<script>
     new Vue({
          el: '#app',
          data: {
               message: 'Easy templating'
          }
     });
</script>

The templating language is tightly coupled into Vue.js. Like many other templating engines, it uses double curly braces {{ }} to bind data to your template. That means the information in our data variable we pass after our new Vue statement is immediately available inside our application. You declare a Vue application using regular JavaScript that passes along a configuration object, which is similar to what you do when you configure an element in jQuery. This configuration object includes things like the element el that you want the application to target in the DOM as well as some JSON data that you want to pass as a variable.

From jQuery’s perspective, you can see that Vue.js is an entirely different animal. Templating or data-binding is something that you have to add to jQuery as additional plug-ins. Let’s look at a more complicated example and the next reason why people are switching to Vue.js.

State vs DOM Management

Another reason why Vue.js is becoming popular is something introduced in other frameworks like React and that is a focus on state, which is the status of the data in your application. In a library like jQuery or regular JavaScript, you have to target some element in the DOM and then do something based on an event related to that element.

Screenshot of the Vue.js app with an arrow pointing to Add Appointment

So, let’s say you wanted to toggle the visibility of an element. In jQuery, you could do something like this:

$('.apt-addheading').on('click',function() {
     $('.card-body').toggle(300);
});

This says, look for an element with a class of apt-addheading, and when the user clicks on it, then look for another element with a class of card-body. If that element is visible, hide it and if that element is hidden, then show it. Vue.js’ approach to this is wildly different:

<div class="panel-heading apt-addheading"
@click="hidepanel=!hidepanel">
     <span class="glyphicon glyphicon-plus"></span> Add Appointment
</div>
<!-- panel-heading -->
<div class="card-body" :class="{ hide: hidepanel }">
...

First, you’ll notice that while we do things in jQuery inside JavaScript and outside our HTML code, in Vue, the JavaScript as well as the HTML live together in one place. The template in Vue.js has HTML code with references to scripts. It’s why the Vue.js version seems longer. In this version, we are tracking the click with the @click event handler. This handler uses a variable called hidepanel. The value of that variable is toggled every time we click on the panel-heading element. In our Vue.js version, the element with the class of card-body gets a parameter called :class that will assign the value of a class called hide if the value of hidepanel is true.

If you’ve never seen this type of coding before, it will probably freak you out, because it requires a shift in thinking. In Vue.js and other modern frameworks, the application’s state is what drives what is happening in your interface. We don’t worry so much about manipulating elements in the DOM because our application ‘reacts’ to the value of data instead. From now on when the value of the hidepanel variable changes, the visibility of that panel changes as well.

So then it become easier to modify your interface because all you have to do is modify the data. Let’s say, for example, that you wanted to hide the panel when a user submits a new appointment. With jQuery, you’d have to remember to issue a .hide() method on the DOM element. With Vue.js, you simply set the hidepanel variable to true. The difference is that with Vue you’re never really worried about what the DOM is doing, you’re always just changing values in your application.

This reminds me of the third reason why people switch to building applications with Vue.js and that’s the Virtual DOM.

Virtual DOM

The virtual DOM isn’t something that’s unique to Vue.js. It’s one of the reasons that the React framework is so popular. The virtual DOM means that the framework takes care of making changes to the DOM for you. The DOM is a representation of what the page looks like. Frameworks like React and Vue.js create an intermediate DOM, called the virtual DOM.

This virtual DOM gets updated only when it needs to be.

Say, for example, that you create an application that shows the first 10 records worth of data and then you fill out a form that causes a record to be added at the end of that list (an 11th record). Instead of redrawing the website, the framework writes the changes to the virtual DOM as if it were the regular DOM. Then Vue.js compares the virtual DOM to the regular DOM. Since you’re only displaying the first 10 records, it notices that no changes need to be made to the real DOM.

Animated GIF of the Vue.js example in action with the Console also in view

If you take a look at this application, you can see that Vue.js injects your DOM with lots of data attributes and updates it on the fly as your data changes. The data drives the interface when you do a search or when you delete an element. Here’s some code for a component in Vue.js that displays this list.

<template>
     <ul class="appointment-list">
          <appointment-item
          v-for="(item, i) in appointments"
          :appointment="item"
          :key="i" />
     </ul>
</template>
<script>
     import AppointmentListItem from './AppointmentListItem.vue';
     export default {
          name: 'AppointmentList',
          props: ['appointments'],
          components: {
               'appointment-item': AppointmentListItem
          }, //components
     } //export
</script>

This code is pretty simple and it doesn’t show the template for the individual list items, which is being imported in line 11. You can find that code here.  But you can see that this component receives some data from the main component in a variable called appointments and then lists the items in that list.

The important thing is that this component has a single, very focused job… to display the list. It doesn’t care about what happens when someone adds or deletes a record. The virtual DOM works with Vue.js to react to changes in our appointments list. When it notices a change, it looks at this component and writes any changes from one of those operations into the virtual DOM. Vue.js then compares that with the actual DOM and updates it only if it needs to. The virtual DOM is Vue.js’ killer app. It just works and makes working with the DOM faster and more efficient.

Components

All modern frameworks like Angular, React and Vue are based on a component architecture. That means that we no longer write huge applications, but break them up into mini components that we put together in order to create larger apps. This is especially powerful when combined with the rest of the reactive virtual DOM we’ve been looking at.

Screenshot of the Vue.js app indicating the three pieces of the application

You can break an application up into pieces and each piece can focus on performing a specialised task. So, you could break an application into a component that displays a list of records, another component that allows you to search through those records and another one that allows you to add a record. Here’s the actual code in our main component.

<template>
     <div id="main-app">
          <add-appointment
          @addRecord="addAppointment" />
          <search-appointments
          :myKey = "filterKey"
          :myDir = "filterDir"
          @searchRecords='searchAppointments'
          @keyChange = "changeKey"
          @dirChange = "changeDir" />
          <appointment-list
          :appointments = 'filteredApts'
          @remove = 'removeItem' />
     </div>
</template>

This code is beautiful in its simplicity, but it also reveals that our components only need to worry about few things. Data is passed to a component via props or properties that look like HTML attributes, so our appointment list gets passed :filteredApts. These are appointments that have been pre-sorted by search or sort. It also receives information should a @remove event take place (more on that later).

The beautiful thing about Vue.js is that our components don’t need to be worried about what the other components need to do. Our list component is only concerned with listing data, our search and our add components only worry about their individual functionality.

Let’s say that our add-appointment component adds a record to our data. Our appointment-list component will simply notice that a change has been made to the app’s data and redraw our list based on the new data. With something like jQuery, you have to do two things, modify the data and update the DOM based on that modification. With Vue.js, you only worry about modifying the data. Each component works independently from each other to do its small tasks. It makes applications easier to manage and update.

If you need to, you handle communication between the components through internal events by emitting custom events when things happen. The events pass information between components and can make it easier to manage the application. That’s another reason people really love these new framework structures.

Event Architecture

Events in Vue.js can help you make your application easier to manage because they can be passed along through the components up to your main application. Let’s take a look at how we would go about deleting a record in our application.

<button @click="requestRemoval">
     ...
     methods: {
          requestRemoval: function() {
               this.$parent.$emit('remove', this.appointment);
          }, //requestremoval

This simplified example from our AppointmentListItem component shows you that you can capture events inside individual components, but because our events are designed to modify data, it’s better to send these events up our component chain to the main component. So we have a local method called requestRemoval() that passes information about the appointment to be deleted to our main App.vue component. This component runs a separate event, called removeItem, that deletes the data. Here’s that entire function.

removeItem: function(apt) {
     this.theAppointments = _.without(this.theAppointments, apt)
}, //removeItem

I’m using the awesome lodash library to remove an element from our data, but you’ll notice that at no time do I worry about the DOM in this sample. I simply have events navigate through the components to modify data. The rest of the app is similar, my search or sort modifies the fiteredApts variable. When that changes, the list will automatically be re-drawn.

Conclusion

Clearly Vue.js presents a new way of thinking about applications. It’s vastly different from the approach you’d use if you were building something with jQuery or JavaScript. Angular gives you some of these features, but has a significantly higher barrier to entry and a much more complex installation process. React is closer in features, but it uses a special language called JSX. While JSX is very similar to the way you work with Vue.js components, Vue.js has a language that is closer to and feels more like JavaScript.

If you really want to see the differences, take a look at the projects I built with jQuery, React and Vue.js. You can also watch my courses Vue.js: Building an Interface and Building a Web Interface with React.js

Subscribe to our monthly Heart Internet newsletter, filled with the latest articles about web design, development, building your business, and exclusive offers.

Subscribe now!

Comments

Please remember that all comments are moderated and any links you paste in your comment will remain as plain text. If your comment looks like spam it will be deleted. We're looking forward to answering your questions and hearing your comments and opinions!

Leave a reply

  • 12/04/2018

    Nice work on this article!

     
  • 14/04/2018

    Hey RAY VILLALOBOS great article!

     

Comments are closed.

Drop us a line 0330 660 0255 or email sales@heartinternet.uk