Replacing jQuery with Vue

2018-06-08 06:39 AM

282

Replacing jQuery with Vue. Did you know that you can incorporate Vue into your project the same way that you would incorporate jQuery — with no build step necessary?

I’m willing to bet that there are a lot of developers out there who still reach for jQuery when tasked with building simple apps. There are often times when we need to add some interactivity to a page, but reaching for a JavaScript framework seems like overkill — with all the extra kilobytes, the boilerplate, the build tools and module bundlers. Including jQuery from a CDN seems like a no-brainer.

In this article, I’d like to take a shot at convincing you that using Vue.js (referred to as Vue from here on), even for relatively basic projects, doesn’t have to be a headache, and will help you write better code faster. We’ll take a simple example, code it up in jQuery, and then recreate it in Vue step by step.

What We’re Building

For this article, we’re going to be building a basic online invoice, using this open-source template from Sparksuite. Hopefully, this should make a refreshing change from yet another to-do list, and provide enough complexity to demonstrate the advantages of using something like Vue while still being easy to follow.

We’re going to make this interactive by providing item, unit price, and quantity inputs, and having the Price column automatically recalculated when one of the values changes. We’ll also add a button, to insert new empty rows into the invoice, and a Total field that will automatically update as we edit the data.

I’ve modified the template so that the HTML for a single (empty) row now looks like this:

This function looks for all item rows in the table and loops over them, passing each row to a calculateSubtotal function, and then summing the results. This total is then inserted into the relevant spot on the invoice.

Lastly, we have a click handler for our Add row button. What we’re doing here is selecting the last item row and creating a duplicate. The inputs of the cloned row are set to default values, and it’s inserted as the new last row. We can also be nice to our users and set the focus to the first input, ready for them to start typing.

Downsides

So what’s wrong with this code as it stands, or rather, what could be better?

You may have heard some of these newer libraries, like Vue and React, claim to be declarative rather than imperative. Certainly looking at this jQuery code, the majority of it reads as a list of instructions on how to manipulate the DOM. The purpose of each section of code — the “what” — is often hard to make out through the details of “how” it’s being done. Sure, we can clarify the intent of the code by breaking it up into well-named functions, but this code is still going to take some effort to mentally parse if you come back to it after a while.

The other issue with code like this is that we’re keeping our application state in the DOM itself. Information about the items ordered exists only as part of the HTML making up the UI. This might not seem like a big problem when we’re only displaying the information in a single location, but as soon as we start needing to display the same data in multiple places in our app, it becomes increasingly complex to ensure that each piece is kept in-sync. There’s no single source of truth.

Although nothing about jQuery prevents us from keeping our state outside of the DOM and avoiding these problems, libraries such as Vue provide functionality and structure that facilitate creating a good architecture and writing cleaner, more modular code.

Converting to Vue

So how would we go about recreating this functionality using Vue?

As I mentioned earlier, Vue doesn’t require us to be using a module bundler, a transpiler, or to opt-in to their single file components (.vue files) in order to get started. Like jQuery, we can simply include the library from a CDN. Let’s start by swapping out the script tag:

The data property is where we store the state of our application. This includes not only any data we want our app to work with, but also information about the state of the UI (for example, which section is currently active in a tab group, or whether an accordion is expanded or contracted).

Vue encourages us to keep our app’s state separate from its presentation (i.e. the DOM) and centralized in one place — a single source of truth.

Modifying the template

Now let’s set up our template to display the items from our data object. As we’ve told Vue we want it to control the table, we can use its template syntax in the HTML to tell Vue how to render and manipulate it.

Using the v-for attribute, we can render a block of HTML for each item in our items array:

<tr class="item" v-for="item in items">
</tr>

Vue will repeat this markup for each element of the array (or object) that you pass to the v-for construct, allowing you to reference each element inside the loop — in this case, as item. As Vue is observing all the properties of the data object, it will dynamically re-render the markup as the contents of items. All we have to do is add or remove items to our app state, and Vue takes care of updating the UI.

We’ll also need to add <input>s for the user to fill out the description, unit price, and quantity of the item:

Here we’re using the v-model attribute to set up a two-way binding between the inputs and properties on our data model. This means any change to the inputs will update the corresponding properties on the item model, and vice versa.

In the last cell, we’re using double curly braces {{ }} to output some text. We can use any valid JavaScript expression within the braces, so we’re multiplying two of our item properties together and outputting the result. Again, as Vue is observing our data model, a change to either property will cause the expression to be re-evaluated automatically.

Events and methods

Now we have our template set up to render out our items collection, but how do we go about adding new rows? As Vue will render whatever is in items, to render an empty row we just need to push an object with whatever default values we want into the items array.

To create functions that we can access from within our template, we need to pass them to our Vue instance as properties of a methods object:

const app = new Vue({
// ...
methods: {
myMethod() {}
},
// ...
})

Let’s define an addRow method that we can call to add a new item to our items array:

Note that any methods we create are automatically bound to the Vue instance itself, so we can access properties from our data object, and other methods, as properties of this.

So, now that we have our method, how do we call it when the Add row button is clicked? The syntax for adding event listeners to an element in the template is v-on:event-name.

<button class="btn-add-row" @click="addRow">Add row</button>

Vue also provides a shortcut for us so we can use @ in place of v-on:, as I’ve shown in the code above. For the handler, we can specify any method from our Vue instance.

Computed properties

Now all we need to do is display the grand total at the bottom of the invoice. Potentially we could do this within the template itself: as I mentioned earlier, Vue allows us to put any JavaScript statement between curly brackets. However, it’s much better to keep anything more than very basic logic out of our templates; it’s cleaner and easier to test if we keep that logic separate.

We could use another method for this, but I think a computed property is a better fit. Similar to creating methods, we pass our Vue instance a computed object containing functions whose results we want to use in our template:

As you might already have noticed, computed properties can be treated as if they were data; we don’t have to call them with parentheses. But, using computed properties has another benefit: Vue is smart enough to cache the returned value and only re-evaluate the function if one of the data properties that it depends upon changes.

If we were using a method to sum up the grand total, the calculation would be performed each and every time the template was re-rendered. Because we’re using a computed property, the total is only recalculated if one of the item’s quantity or price fields are changed.

Filters

You might have spotted we have a small bug in our implementation. While the unit costs are whole numbers, our total and subtotals are displayed without the cents. What we really want is for these figures to always be displayed to two decimal places.

Rather than modify both the code that calculates the subtotals and the code that calculates the grand total, Vue provides us with a nice way to deal with common formatting tasks like this: filters.

As you might have already guessed, to create a filter we just pass an object with that key to our Vue instance:

Summing Up

Comparing the two versions of the code side by side, a couple things stand out about the Vue app:

The clear separation between the UI, and the logic/data that drives it: the code is much easier to understand, and lends itself to easier testing

The UI is declarative: you only need concern yourself with what you want to see, not how to manipulate the DOM to achieve it.

The size (in KB) of both libraries is almost identical. Sure, you could slim down jQuery a bit with a custom build, but even with a relatively simple project such as our invoice example, I think the ease of development and the readability of the code justifies the difference.

Vue can also do a lot more than we’ve covered here. Its strength lies in allowing you to create modular, reusable UI components that can be composed into sophisticated front-end applications. If you’re interested in delving deeper into Vue, I’d recommend checking out Getting Up and Running with the Vue.js 2.0 Framework.