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

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 a single page application, it's can be a bit much to setup 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:

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 setup a new Vue instance and target theeventssection 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 setup 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.

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 obviously going to be responsible for adding new events in. We'll add this method in now and also prime the application with some data.

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 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.

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 setup 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.

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 which 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:

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 setup 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.

Wrapping Up

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.