Getting Started with VueJS

In this article, we will go through VUEJS. We’re in a golden era of JavaScript libraries and frameworks. More and more companies are building out full, dynamic web apps in addition to – or in lieu of – traditional desktop applications. This means things are constantly changing and frameworks are going in and out of vogue, but the core concepts of what we’re trying to accomplish remain similar.

Why use Vue?

When comparing it with its competitors, including Angular, React, Ember, Aurelia, etc., Vue boasts of beating some of them in certain aspects. These aspects include simple API, size, performance, learning curve, etc. You can have a look at these comparisons on the official documentation.

And as you may or may not know already, the most important of all is not these tools—it’s really about you, your client, your team, and the project. It is recommended to choose what blends in well and if Vue does, read on.

Requirements

Vue requires as little as just a single script to experience its awesomeness. And for this tutorial, we can make use of Fiddle and we need not acquire the luxury of tooling on our machine to start building. This will also help us see some of our code come to life, instantly.

Create an empty Fiddle and add the following script to the HTML:

<script src="https://unpkg.com/vue@next/dist/vue.js"></script>

The script loads Vue into the Fiddle environment and from now on, we can use whatever API Fiddle can offer.

The Vue Instance

The entry point of every Vue application is created via an instance. The instance then configures the rest of the application and can drill into child members while your application scales up. This is how one would look like:

// Vue instance
new Vue({
// Element to attach the app
// on the DOM
  el: '#application',
  // Bindable data
  data: {
    message: 'Welcome to Team',
  }
})

The instance is configured by passing in an object containing information about the app and where it should be loaded.

The el property specifies which element it should be mounted on and the value is the ID of the element prefixed with a hash (#).

The data to be bound to the view is specified with the data property, which has an object of values that can be accessed via the template.

Back in the HTML, we can display the data using what is called reactive binding:

<div id="application">
  <p>{{ message }}</p>
</div>

Two things worth noticing

the div with the ID app is where we mount the application; and

the double curly braces are used to bind the data to the template.

We are binding the message value which is specified in the data object during configuration.

Getting started is that simple and we already have a working app without the drama:

Data-Binding

We already saw a good example of binding data to view but there is more to that in a real application. Let’s drill it down more and see what Vue can do for us:

Conditions

A very useful feature in JS frameworks is the ability to bind data to view prior to a decision. We can tell Vue to make a binding only if a value resolves to true. Let’s see how:

new Vue({
  el: '#application',
  data: {
    message: 'Welcome to Team!',
    // Flag to check if user
    // is a new member or not
    newMember: true
  }
})

We just added an extra data to check if the user is new or not. If it’s true that the user just joined, else he/she is not a new member.

Let’s use the flag to display different messages to application users:

<div id="application">
  <!-- Shown if the user is new -->
  <h2 v-if="newMember">{{ message }}</h2>
  <!-- Shown if the user is NOT new -->
  <h2 v-else="newMember">Pick a Mentor</h2>
</div>

v-if and v-else are responsible for displaying data conditionally. If the value being evaluated (which is newMember) resolves to true, the template with the v-if directive wins, if falsev-else wins.

Loops

Vue is awesome enough to offer us a simple API to loop through an array of bound data. The v-for directive takes its use for this purpose and all we just need is an array of data:

<ol>
    <li v-for="mentor in mentors">{{mentor.fullname}}</li>
  </ol>

v-for accepts a loop expression which creates a variable mentor and uses the variable to iterate over an array of mentors. The array contains the object so we can then access the properties:

new Vue({
  el: '#application',
  data: {
    message: 'Welcome to Team',
    newMember: false,
    mentors: [
        {id: "ABC", fullname: "ABC"},
      {id: "DEF", fullname: "DEF"},
      {id: "GHI", fullname: "GHI"},
      {id: "JKL", fullname: "JKL"},
      {id: "MNO", fullname: "MNO"},
      {id: "PQR", fullname: "PQR"}
    ]
  }
})

You can see the array that contains a list of mentors which the v-for directive is iterating over.

Two-Way Binding

Two-way binding in Vue is very straight forward and is achievable with just a directive known as v-model. Let’s see two-way binding in play by attaching the v-model directive to a text input and display the data at the same time:

<p>
    Add mentor: <input type="text" v-model="mentor"> 
    {{mentor}}
  </p>

The value of the directive is used for the data-binding and that is why the content of the interpolation ({{}}) is the same with that of the directive. We now need to specify the data in our Vue configuration:

new Vue({
  el: '#app',
  data: {
    message: 'Welcome to Team',
    // For the two-way binding
    mentor: '',
    newMember: false,
    mentors: [
        // Truncated for brevity
    ]
  }
})

Events and Handlers

Event is the story behind user interaction in any web application. For that reason, Vue has a very declarative syntax which is simple to comprehend and remember for creating and handling events.

Let’s first add more controls to our view which we will use to collect the mentor’s full name and ID.

<p>
    ID: <input type="text" v-model="mentor.id"> 
     {{mentor.id}}
</p>
<p>
    Fullname: <input type="text" v-model="mentor.fullname"> 
    {{mentor.fullname}}
</p>
<p>
    <button v-on:click="addMentor">Add Mentor</button>
</p>

Just the usual binding but this time, we are binding to the values of an object and not just a direct primitive value.

Furthermore, we also added a button to an event. Events in Vue are created with the v-on directive while attaching the kind of event using :. Eg: v-on:clickv-on:mouseover, etc. The click event takes a handler, addMentor which we are yet to implement. Before the implementation of this event, update the mentor data in the Vue config to an object rather than a primitive:

mentor: {id:'',fullname:''},

Event handlers are specified just like bound data are but not directly inside the data object, rather, in a methods object:

new Vue({
  el: '#app',
  data: {
    message: 'Welcome to Team',
    // No longer a primitive
    mentor: {id:'',fullname:''},
    newMember: false,
    mentors: [
        // Truncated for brevity
    ]
  },
  // Methods
  methods: {
    // Add mentor handler
      addMentor: function(){
        // Add new value from the inputs
        // above the existing array
        this.mentors.unshift(this.mentor)
    }
  }
})

The addMentor property has a function value which tells our app what to do when the button is clicked. What it does is update the array of mentors by dropping our new mentor above the array using unshift.

Meet Components

If your concern is whether or not you can enjoy components just like you do in other frameworks or libraries, then you can stop worrying because you can. In fact, components are recommended in Vue projects because just as we can see, our app is already getting bigger.

Let’s create a mentor-user component that just receives data from our app and displays the data:

// mentor-user component
Vue.component('mentor-user', {
    // acceptable props
    props: ['mentor'],
    // renderable templates
    template: '<li>{{mentor.fullname}}</li>'
});

Components are created with Vue.component which takes two arguments — a component name/identifier and a configuration.

The config object specifies the template that the component will inject to the DOM and the props expected from the parent of the component. The parent is that itself so let’s see how the parent calls it:

<ol>
    <mentor-user v-for="mentor in mentors" v-bind:mentor="mentor"></mentor-user>
  </ol>

We render the component using the identifier specified while creating the component. We also pass in the props using v-bind:[PROP_NAME] where PROP_NAME is the name the property and in our case, mentor. The value of the property is received from the loop.

This might not seem so useful for the size of our app but once an app scales, the portion taken care of by the component might require more and more DOM items.

Modern front-end development is still pretty chaotic, but it doesn’t mean you have to lose your mind. If you’re looking for a great place to start, you really don’t need to look any further than Vue, and if you’re still skeptical about using a relatively lesser known library, know that it is already being used in production by many companies right now, including my own, Dotdash.

One such usage is on VeryWell Fit, where Vue is used to power a recipe calorie and nutrition calculator. You simply enter your ingredients and watch as it returns to you the calories of your meal and the relevant nutritional facts.

Leave a Reply

Your email address will not be published. Required fields are marked *