Replacing jQuery With Vue.js

Replacing jQuery With Vue.js

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

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:

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/[email protected]/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:

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.

Understand and Use JavaScript's .forEach() vs. jQuery's .each()

Understand and Use JavaScript's .forEach() vs. jQuery's .each()

There are two functions to deal with an array on the client-side – JavaScript's .forEach() and jQuery's .each(). Here, I will teach you how to use both of these methods with some sample code.

Your knowledge of JavaScript and jQuery is incomplete if you don't know how to loop with .forEach() and .each() methods. This tutorial helps you to quickly master JavaScript .forEach() & jQuery .each() in 2 minute time.

There are two methods to deal with an array on client-side – JavaScript .forEach() and jQuery .each(). Here, I will teach you how to use both of these methods in different scenarios.

Defination of these 2 methods

a. JavaScript .forEach() Method

The .forEach() method of JavaScript executes a given function once for each element of the array.

For example -

var arr = ['a', 'b', 'c'];    
arr.forEach(function(element) {  
    console.log(element);  
});  

The above JavaScript code will print – ‘a’, ‘b’, & ‘c’ in the console window.

b. jQuery .each() Method

jQuery has it’s own method called jQuery Each method and it is used to loop over arrays, array of object and matched elements of the DOM. See the below code:

var arr = ['a', 'b', 'c'];  
$.each(arr , function (index, value){  
  console.log(arr);   
});  

The above jQuery code will print – ‘a’, ‘b’, & ‘c’ in the console window.

Looping through DOM elements

a. JavaScript .forEach() Method

Suppose you want to extract all the anchor tags from the web page, and then loop through each of them. In that case first you have to get all the anchors using document.getElementsByTagName("a") and then convert it into an array. This is because JavaScript .forEach() method loops only through an array.

See the below code:

var links = document.getElementsByTagName("a");    
var Arr = Array.from(links);    
Arr.forEach(someFunction);    
    
function someFunction(currentValue) {    
    console.log(currentValue);    
}    

I used Array.from() method to convert to an array.

b. jQuery .each() Method

In case of .each() method you simply loop through all the anchor tags, like shown in the below code, as jQuery Each method can loop through arrays, array of objects and matched element of the DOM. So you don’t have to do the conversion to an array like JavaScript .forEach() method.

See the below code:

$("a").each(function (index, value) {   
  console.log($(this).attr("href"));   
});  

Clearly you can see in this case the lines of codes are very less than compared to .forEach() method of JavaScript.

Which one you should choose?

Case 1: DOM Manipulations

When working with DOM elements the jQuery Each method has a great advantage because it removes a lot of code lines. So prefer this method during DOM manipulations.

Case 2: Website is using jQuery from before

If your website is already using jQuery then you should use jQuery Each method because this will bring code consistency in your project.

In all other cases use JavaScript .forEach() method.

Conclusion

Both of these above methods are very good and they make the codes easy to understand. I would recommend every web developer to know both of these methods.

Thank you for reading.

jQuery vs Vanilla JavaScript - Beau teaches JavaScript

jQuery vs Vanilla JavaScript - Beau teaches JavaScript

When should you use jQuery instead of vanilla JavaScript? Is jQuery still relevant? What is jQuery good for? jQuery vs vanilla JavaScript - Beau teaches JavaScript

When should you use jQuery instead of vanilla JavaScript? Is jQuery still relevant? What is jQuery good for? Find out in this video!

3 JavaScript libraries to replace jQuery

3 JavaScript libraries to replace jQuery

Ubiquitous jQuery has been outmoded by JavaScript and browser advances. Cash, Zepto, and Syncfusion are three JavaScript libraries picking up where jQuery left off

Simplifying tasks such as HTML document traversal, animation, and event handling, the stalwart jQuery JavaScript library changed the face of web development. As of May 2019, **jQuery **is still being used in 74 percent of known websites, according to web technology surveyor W3Techs. Nevertheless, the jQuery library, which debuted in August 2006, is now being viewed by some developers as an older technology whose time has passed.

Alternatives to **jQuery **have emerged in recent years, such as the Cash library or even just modern, vanilla JavaScript, now that web browsers all handle **JavaScript libraries **the same way and jQuery is no longer needed to solve compatibility issues. Arguments on Reddit and videos on YouTube make the case that jQuery has become obsolete, or at least is not as essential as it once was.

Why jQuery is no longer needed

In one YouTube presentation, “Is jQuery still relevant in 2018?,” web development educator Brad Traversy acknowledges that jQuery is probably the best generalized JavaScript library ever created. It is easy to learn, cross-browser compatible, more concise than older vanilla JavaScript, and rich in plug-ins offering specific functionality. But JavaScript has advanced far since ECMAScript 6, and jQuery is no longer needed in many situations, Traversy concludes.

In another video, coding educator Kenneth Lowrey argues that becoming fluent in jQuery is a waste of time. In the current web development landscape, modern browsers handle JavaScript the same, for the most part. In most cases, native JavaScript code is better than a “bloated legacy library like jQuery,” he says.

While jQuery had been the choice for making HTTP requests, for example, ECMAScript 6 brought forth Fetch, a promised-based API that makes HTTP requests easier. And the advancement does not stop with HTTP. Where jQuery has utilities for tasks such as manipulating arrays, vanilla JavaScript now has improved accommodations for these operations, too.

Animations are still more difficult with vanilla JavaScript than jQuery, but there are other options such as CSS transitions or keyframes, Traversy points out. The third-party GreenSock library also can be used for animations. For DOM manipulation, a task once ruled by jQuery, native browser APIs have closed the gap.

For tasks that cannot be done in vanilla JavaScript, Traversy recommends specialized libraries, instead of a generalized library like jQuery. Traversy also recommends using JavaScript frameworks such as React, Angular, or Vue for mid-size and large applications. Traversy still recommends jQuery for use on simple sites with no framework.

jQuery alternatives

What should you use instead of jQuery? Besides modern, vanilla JavaScript, a short list of jQuery alternatives includes Cash, Zepto, and Syncfusion Essential JS 2. Cash and Zepto are open source JavaScript libraries available under an MIT license. Syncfusion Essential JS 2 is a commercial product.

Cash

Cash has more than 3,570 stars on GitHub. Billed as an “absurdly small jQuery alternative” for modern browsers, Cash has a jQuery-style syntax for manipulating the DOM and takes up 32KB of space, uncompressed. Cash supports capabilities including namespaced events, TypeScript types, and modern builds. You can download Cash from GitHub.

Zepto

Zepto is described as “a minimalist **JavaScript library **with a largely jQuery-compatible API.” Developers who know jQuery already know how to use Zepto, its makers go on to say. Zepto purports to be much smaller and faster-loading than jQuery, and can work with the PhoneGap toolset for mobile and desktop browsers. You can download Zepto from the project website.

Syncfusion Essential JS 2

Syncfusion Essential JS 2 is a commercially licensed JavaScript UI controls library written in TypeScript. Serving as an alternative to the jQuery UI library, Syncfusion is designed to be a low-overhead, lightweight, and modular library to improve web applications. Syncfusion supports frameworks including Angular, React, and Vue. You can purchase Syncfusion Essential JS 2 or download a free trial from the Syncfusion website. Complete source code, unit test files, test scripts, and live demos are available on GitHub.