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

Build an #app with #VueJS: A lightweight alternative to #AngularJS  #JavaScript

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

  • — index.html —

    div class=”panel-heading”
    h3Add 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” /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: 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.

  • // 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.’

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

  • — index.html —

    div class=”list-group”

    a href=”#” class=”list-group-item” v-repeat=”event in events”
    h4 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: /a

    /div

    As you can see, we’re using Vue’s v-repeat on the a tag to loop over the events data.

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.

@starliftorg: Build an #app with #VueJS: A lightweight alternative to #AngularJS #JavaScript

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.

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.

package to send HTTP requests to a back end.

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.

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

We’ll also need to create the main files:

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.

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

key.

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

for selecting the event date. NOTE: This will not work in Firefox.

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.

method would be called when a keystroke is finished.

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

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.

// 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: ” }; } } } …

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.

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.

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.

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

values within various elements to display the events data.

method.

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

for deleting events set up, lets now create the method that should be called when it is clicked.

convenience method which takes care of finding the index passed in from the view and removing the element from the DOM.

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

method up to send the request:

requests to add data:

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.

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.

method.

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.

If you’d like to get more tutorials like this one, feel free to head over to my website and signup for my mailing list. You should follow me on Twitter—I’d love to hear about what you’re working on!

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

You might also like More from author

Comments are closed, but trackbacks and pingbacks are open.