Want to learn Vue.js from the ground up? Get an entire collection of Vue books covering fundamentals, projects, tips and tools & more with SitePoint Premium. Join now for just $14.99/month.
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:
<tr class="item">
<td><input value="" /></td>
<td>$<input type="number" value="0" /></td>
<td><input type="number" value="1" /></td>
<td>$0.00</td>
</tr>
jQuery
So, first of all, let’s take a look at how we might do this with jQuery.
$('table').on('mouseup keyup', 'input[type=number]', calculateTotals);
We’re attaching a listener to the table itself, which will execute the calculateTotals
function when either the Unit Cost or Quantity values are changed:
function calculateTotals() {
const subtotals = $('.item').map((idx, val) => calculateSubtotal(val)).get();
const total = subtotals.reduce((a, v) => a + Number(v), 0);
$('.total td:eq(1)').text(formatAsCurrency(total));
}
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.
function calculateSubtotal(row) {
const $row = $(row);
const inputs = $row.find('input');
const subtotal = inputs[1].value * inputs[2].value;
$row.find('td:last').text(formatAsCurrency(subtotal));
return subtotal;
}
In the code above, we’re grabbing a reference to all the <input>
s in the row and multiplying the second and third together to get the subtotal. This value is then inserted into the last cell in the row.
function formatAsCurrency(amount) {
return `$${Number(amount).toFixed(2)}`;
}
We’ve also got a little helper function that we use to make sure both the subtotals and the total are formatted to two decimal places and prefixed with a currency symbol.
$('.btn-add-row').on('click', () => {
const $lastRow = $('.item:last');
const $newRow = $lastRow.clone();
$newRow.find('input').val('');
$newRow.find('td:last').text('$0.00');
$newRow.insertAfter($lastRow);
$newRow.find('input:first').focus();
});
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.
Here’s the completed jQuery demo:
See the Pen jQuery Invoice by SitePoint (@SitePoint) on CodePen.
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 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 use a module bundler, or 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:
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
The next thing we need to do is create a new Vue instance:
const app = new Vue({
el: 'table'
});
The only option we need to provide here is el
, which is a selector (like we would use with jQuery) identifying which part of the document we want Vue to manage.
We can put Vue in charge of anything from the entire page (for a single page application, for example) or a single <div>
. For our invoice example, we’ll give Vue control of the HTML table.
Data
Let’s also add the data for the three example rows to our Vue instance:
const app = new Vue({
el: 'table',
data: {
items: [
{ description: 'Website design', quantity: 1, price: 300 },
{ description: 'Hosting (3 months)', quantity: 1, price: 75 },
{ description: 'Domain name (1 year)', quantity: 1, price: 10 },
]
}
});
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 (that is, 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
change. 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:
<td><input v-model="item.description" /></td>
<td>$<input type="number" v-model="item.price" /></td>
<td><input type="number" v-model="item.quantity" /></td>
<td>${{ item.price * item.quantity }}</td>
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:
methods: {
addRow() {
this.items.push({ description: '', quantity: 1, price: 0 });
},
},
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:
const app = new Vue({
// ...
computed: {
total() {
return this.items.reduce((acc, item) => acc + (item.price * item.quantity), 0);
}
}
});
Now we can reference this computed property within our template:
<tr class="total">
<td colspan="3"></td>
<td>Total: ${{ total }}</td>
</tr>
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 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:
const app = new Vue({
// ...
filters: {
currency(value) {
return value.toFixed(2);
}
}
});
Here we’ve created a very simple filter called currency
, which calls toFixed(2)
on the value it receives and returns the result. We can apply it to any output in our template like so:
<td>Total: ${{ total | currency }}</td>
Here’s the completed Vue demo:
See the Pen Vue Invoice by SitePoint (@SitePoint) on CodePen.
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.
Frequently Asked Questions (FAQs) on Replacing jQuery with Vue
What are the key differences between jQuery and Vue.js?
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, and animation much simpler with an easy-to-use API that works across a multitude of browsers. On the other hand, Vue.js is a progressive JavaScript framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries or existing projects.
Why should I consider replacing jQuery with Vue.js?
While jQuery has been a reliable tool for many years, Vue.js offers a more modern and comprehensive approach to building web applications. Vue.js is component-based, which promotes reusability and maintainability. It also has a more robust ecosystem, with tools for state management, routing, and more. Additionally, Vue.js has a virtual DOM, which can lead to better performance in some cases.
How can I convert jQuery code to Vue.js?
Converting jQuery code to Vue.js involves understanding the equivalent Vue.js methods and properties for jQuery functions. For instance, instead of using jQuery’s $(document).ready()
, you would use Vue’s mounted()
lifecycle hook. Similarly, instead of using jQuery’s $.ajax()
, you would use Vue’s axios
or fetch
for making HTTP requests.
Can I use jQuery and Vue.js together in a project?
While it’s technically possible to use jQuery and Vue.js together, it’s generally not recommended. Mixing the two can lead to confusing code and potential conflicts, as both libraries try to manage the DOM in their own way. It’s better to fully commit to one or the other.
How can I handle events in Vue.js as compared to jQuery?
In jQuery, you typically use methods like .click()
, .on()
, or .bind()
to attach event listeners to elements. In Vue.js, you use the v-on
directive (or its shorthand @
) to listen to DOM events and run some JavaScript when they’re triggered.
How does data binding work in Vue.js compared to jQuery?
jQuery doesn’t have built-in data binding. You manually select elements and update their content. In contrast, Vue.js has a powerful system for data binding. You can use the v-model
directive to create two-way data bindings on form input, textarea, and select elements.
How can I animate elements in Vue.js as compared to jQuery?
jQuery has built-in methods for animations like .fadeIn()
, .slideUp()
, etc. Vue.js, on the other hand, provides transition components that allow for more flexibility when animating elements in and out of the DOM.
How can I make HTTP requests in Vue.js as compared to jQuery?
In jQuery, you typically use the $.ajax()
method to make HTTP requests. Vue.js doesn’t have a built-in method for this, but you can use modern APIs like fetch
or libraries like axios
to make HTTP requests.
How does Vue.js handle reactivity compared to jQuery?
jQuery doesn’t have a built-in system for reactivity. You manually update the DOM when your data changes. Vue.js, on the other hand, has a reactive data system. When you change a piece of data, the view updates automatically.
How can I replace jQuery plugins with Vue.js components?
Many jQuery plugins can be replaced with Vue.js components. Vue.js has a rich ecosystem with thousands of open-source components available. You can also create your own custom components. This promotes reusability and maintainability in your code.
Nilson is a full-stack web developer who has been working with computers and the web for over a decade. A former hardware technician, and network administrator. Nilson is now currently co-founder and developer of a company developing web applications for the construction industry. You can also find Nilson on the SitePoint Forums as a mentor.