Tutorial

Build an App with Vue.js: A Lightweight Alternative to AngularJS

Draft updated on Invalid Date
Default avatar

By Ryan Chenkie

Build an App with Vue.js: A Lightweight Alternative to AngularJS

This tutorial is out of date and no longer maintained.

Introduction

Front-end frameworks like AngularJS allow us to build out very nice single-page applications easily, especially when we become well versed with all the concepts.

However, for many projects, frameworks like Angular can actually be a little bit more than what we need.

If all we want to do is implement a few features in a single-page application, it’s can be a bit much to set up the necessary config, routing, controllers, services, and more that make up an Angular app.

For something more lightweight, a great solution is Vue.js. Vue is a library that focuses heavily on the ViewModel – the two-way data bindings that tie what we see and interact with on the screen with the application’s data model. In this way (and as stated on the Vue.js website), the library is “not a full-blown framework - it is designed to be a view layer that is simple and flexible”.

For many use cases, this is awesome because it means we can get the benefits of a single-page(ish) application without the overhead that can come with using larger frameworks.

In this tutorial we will be building a simple events bulletin board application that will allow users to add and remove events. To explore Vue’s main features we will simply be working with local data on the client-side, but towards the end, we’ll see how we can use the vue-resource package to send HTTP requests to a back-end.

Similarities to AngularJS

If you’re familiar with AngularJS, you’ll likely notice a lot of similarities between it and Vue.js as we go. Vue is heavily influenced by Angular and this actually works to our benefit because concepts transfer nicely between the two.

Installing the Dependencies

Let’s first grab Vue.js, Vue Resource, and Bootstrap with npm. From the command line:

  1. npm install vue vue-resource bootstrap

We’ll also need to create the main files:

  1. touch index.html app.js

Setting Up the HTML

index.html
    <!doctype html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Vue</title>

      <!-- CSS -->
      <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
    </head>
    <body>

      <!-- navigation bar -->
      <nav class="navbar navbar-default">
        <div class="container-fluid">
          <a class="navbar-brand"><i class="glyphicon glyphicon-bullhorn"></i> Vue Events Bulletin Board</a>
        </div>
      </nav>

      <!-- main body of our application -->
      <div class="container" id="events">

        <!-- add an event form -->
        <div class="col-sm-6">
          <div class="panel panel-default">
            <div class="panel-heading">
              <h3>Add an Event</h3>
            </div>
            <div class="panel-body">

            </div>

          </div>
        </div>

        <!-- show the events -->
        <div class="col-sm-6">
          <div class="list-group">

          </div>
        </div>
      </div>

      <!-- JS -->
      <script src="node_modules/vue/dist/vue.js"></script>
      <script src="node_modules/vue-resource/dist/vue-resource.js"></script>
      <script src="app.js"></script>
    </body>
    </html>

The main <div> with an ID of events is our target area for the application. As we’ll see in the next section, we need to create a Vue instance for each part of the application that we want to target.

In Angular, we can limit our application modules to certain parts of the HTML with ng-app="{module}". Vue works in a similar way. When we set up the Vue instance, we define an element to target, and anything within that element will be available to the application.

Creating a Vue Instance

Within app.js, let’s set up a new Vue instance and target the events section of the HTML by setting it on the el key.

app.js
    new Vue({
    // We want to target the div with an id of 'events'
      el: '#events'
    });

At this point, Vue is available anywhere within div#events. Before setting up the rest of the HTML, let’s set up the other keys that we’ll need for our Vue instance and cover what they are responsible for.

app.js
    new Vue({

      // We want to target the div with an id of 'events'
      el: '#events',

      // Here we can register any values or collections that hold data
      // for the application
      data: {},

      // Anything within the ready function will run when the application loads
      ready: function() {},

      // Methods we want to use in our application are registered here
      methods: {}
    });
  • The data key will be the object where all our ViewModel data is registered
  • The ready function will run when the application loads and is useful for calling other methods to initialize the app with data
  • The methods key is where we can register custom methods for the application

Adding the Form

Our form will need inputs for the event details. We’ll use the native HTML5 datepicker for selecting the event date. NOTE: This will not work in Firefox.

index.html
    ...

    <div class="panel-heading">
      <h3>Add an Event</h3>
    </div>
    <div class="panel-body">

      <div class="form-group">
        <input class="form-control" placeholder="Event Name" v-model="event.name">
      </div>

      <div class="form-group">
        <textarea class="form-control" placeholder="Event Description" v-model="event.description"></textarea>
      </div>

      <div class="form-group">
        <input type="date" class="form-control" placeholder="Date" v-model="event.date">
      </div>

      <button class="btn btn-primary" v-on="click: addEvent">Submit</button>

    </div>

    ...

You’ll notice that we’re adding a directive called v-model to our input and textarea elements and we’re assigning distinct spots on an event object to each. Just like with ng-model in Angular, the values that we type into these fields will be bound to the ViewModel and will be available for use elsewhere in the application.

The submit button element has the v-on directive with a value of "click: addEvent" on it. This works much the same way that ng-click does with Angular: we pass a method to be run on the click event. The difference that Vue introduces is that we can use the v-on directive to specify the type of event we want the element to respond to. For example, we could say v-on="keyup: addEvent" and the addEvent method would be called when a keystroke is finished.

If we view the app in the browser, we see that we get our form:

Adding Event Data

The addEvent method we added to the click event in the last section is going to be responsible for adding new events. We’ll add this method now and also prime the application with some data.

app.js
    ...

    data: {
      event: { name: '', description: '', date: '' },
      events: []
    },

    // Anything within the ready function will run when the application loads
    ready: function() {
      // When the application loads, we want to call the method that initializes
      // some data
      this.fetchEvents();
    },

    // Methods we want to use in our application are registered here
    methods: {

      // We dedicate a method to retrieving and setting some data
      fetchEvents: function() {
        var events = [
          {
            id: 1,
            name: 'TIFF',
            description: 'Toronto International Film Festival',
            date: '2015-09-10'
          },
          {
            id: 2,
            name: 'The Martian Premiere',
            description: 'The Martian comes to theatres.',
            date: '2015-10-02'
          },
          {
            id: 3,
            name: 'SXSW',
            description: 'Music, film and interactive festival in Austin, TX.',
            date: '2016-03-11'
          }
        ];
        // $set is a convenience method provided by Vue that is similar to pushing
        // data onto an array
        this.$set('events', events);
      },

      // Adds an event to the existing events array
      addEvent: function() {
        if(this.event.name) {
          this.events.push(this.event);
          this.event = { name: '', description: '', date: '' };
        }
      }
    }
    ...

On the data key, we are registering both the event object that will hold our form data, as well as an empty events array that will be populated with data when the application loads. If we didn’t pre-initialize the event object by registering it on the data key, we would still get values from our form as expected. However, by initializing it we get “more reliable reactivity and better performance” as a warning message in the console reveals.

Within the ready function we are calling fetchEvents which is a method that takes some data and uses Vue’s $set to put it onto the events array. The $set method is provided by Vue and when used to put data onto an array, triggers a view update. Its first argument needs to be a string with the name of the keypath that we want to target.

Finally, the addEvent method first checks to make sure we at least have a value present for event.name and if so, pushes the event onto the events array. After this, the form is cleared by setting the event object keys back to empty strings. We’re ready to view existing listings and add new ones, but we’ll need some HTML to display them.

Adding the Listing Area

To list out the events, we’ll need HTML in which we will include some templating.

index.html
    ...

    <div class="list-group">

      <a href="#" class="list-group-item" v-repeat="event in events">
        <h4 class="list-group-item-heading">
          <i class="glyphicon glyphicon-bullhorn"></i>
          {{ event.name }}
        </h4>

        <h5>
          <i class="glyphicon glyphicon-calendar" v-if="event.date"></i>
          {{ event.date }}
        </h5>

        <p class="list-group-item-text" v-if="event.description">{{ event.description }}</p>

        <button class="btn btn-xs btn-danger" v-on="click: deleteEvent($index)">Delete</button>
      </a>

    </div>

    ...

As you can see, we’re using Vue’s v-repeat on the a tag to loop over the events data. As you’re probably thinking, v-repeat works just like Angular’s ng-repeat. Templating works the same way as it does in Angular as well – we use the double curly braces to render data. In this case, we access the name, date, and description values within various elements to display the events data.

The button at the bottom triggers a click event that calls deleteEvent, which we have yet to create. This method accepts Vue’s $index property as an argument. This property gives us the index of the current element within the v-repeat loop and will be used to remove that element once we set up the deleteEvent method.

If we refresh the page, we see that we get the events data displayed and that we can also add in new events.

We’ve already got the button for deleting events set up, lets now create the method that should be called when it is clicked.

app.js
    ...

    deleteEvent: function(index) {
      if(confirm("Are you sure you want to delete this event?")) {
        // $remove is a Vue convenience method similar to splice
        this.events.$remove(index);
      }
    }

    ...

In this method, we are first prompting the user to confirm that they actually want to delete the event. If they click OK, the event is removed by using Vue’s $remove convenience method which takes care of finding the index passed in from the view and removing the element from the DOM.

Switching to a Back End

Like AngularJS, Vue is totally agnostic about the back end that we use for our applications. Just as long as the server responds to HTTP requests with JSON, we can use Vue Resource to handle data retrieval.

As previously mentioned, we won’t actually set up a back end in this tutorial, but we will show how to make the appropriate HTTP requests to one. A NodeJS back end would be an easy solution for a Vue app, and you can learn how to set one up with Scotch.io’s Mean Machine eBook (you’ll just need to swap out the Angular stuff for Vue).

The first step would be to move the events data over to the server and set up an endpoint that would take care of serving the events. Ideally, we would have an endpoint that would respond to a GET request at something like api/events. We would then change our fetchEvents method up to send the request:

app.js
    ...

    // If we had a back end with an events endpoint set up that responds to GET requests
    this.$http.get('api/events').success(function(events) {
      this.$set('events', events);
    }).error(function(error) {
      console.log(error);
    });

    ...

In the success handler of the GET request, we are still using $set to put the returned data onto the events array. We could also make POST requests to add data:

app.js
    ...

    // If we had an endpoint set up that responds to POST requests
    this.$http.post('api/events', this.event).success(function(response) {
      this.events.push(this.event);
      console.log("Event added!");
    }).error(function(error) {
      console.log(error);
    });

    ...

In this case, we are sending the event object that contains the form data by including it as the second argument to the call. In the success handler, we are pushing the event onto the array to update the view, much like we were before.

Another way we could update the view is by making an additional GET request to retrieve the total list in the success handler, but this requires another network request which isn’t ideal. Deleting an event is simple as well.

app.js
    ...

    // We could also delete an event if we had the events endpoint set up to delete data
    this.$http.delete('api/events/' + event.id).success(function(response) {
      this.events.$remove(index);
    }).error(function(error) {
      console.log(error);
    });

    ...

In this case, we are tacking the event.id onto the end of the route for our DELETE request which, if our API is set up to do it, will delete the record based on that ID. For this to work, we would need to pass event into the method call from the view and then receive it on the deleteEvent method.

Conclusion

Vue.js offers us a great alternative to larger frameworks like AngularJS and is a perfect solution for cases in which we want to easily create single-page apps without a lot of overhead. The library is flexible and easy to work with and if you have experience with Angular, you’ll feel right at home.

To build a full-fledged single-page application with Vue, we can use vue-router which integrates with the Vue.js core to handle routing.

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
Ryan Chenkie

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