Table of Contents
Key Points
What we will build
jQuery implementation
Convert to Vue
Summary
FAQs about replacing jQuery with Vue
What is the main difference between jQuery and Vue.js?
Why should I consider replacing jQuery with Vue.js?
How to convert jQuery code to Vue.js?
Can I use jQuery and Vue.js in one project?
How to handle events in Vue.js, compared to jQuery?
How does data binding in Vue.js work compared to jQuery?
How to animate elements in Vue.js, compared to jQuery?
How to make HTTP requests in Vue.js, compared to jQuery?
How does Vue.js handle reactiveness, compared to jQuery?
How to replace jQuery plugin with Vue.js component?
Home Web Front-end JS Tutorial How to Replace jQuery with Vue

How to Replace jQuery with Vue

Feb 14, 2025 am 09:56 AM

Say goodbye to jQuery and embrace Vue.js: build a simpler and more efficient web application

How to Replace jQuery with Vue

Want to learn Vue.js from scratch? Join SitePoint Premium now to get a complete collection of Vue.js books covering Vue.js basics, project practices, tips and more for just $14.99 per month!

Many developers still rely on jQuery when building simple applications. While sometimes you only need to add a small amount of interactivity to your page, using JavaScript frameworks seems too complicated - extra code volume, boilerplate code, build tools and module packers, and more. Introducing jQuery from CDN seems like a breeze to choose.

This article is intended to convince you that even for relatively simple projects, using Vue.js (hereinafter referred to as Vue) does not require any effort, but will help you write better code faster. We will take a simple example as an example to encode using jQuery and Vue respectively, and gradually demonstrate its differences.

Key Points

  • Replace jQuery with Vue.js for basic projects is not difficult, and it can write better, faster code.
  • Vue.js allows the UI to be clearly separated from the logic/data that drives it, making the code easier to understand and test.
  • The UI in Vue.js is declarative, which means developers only need to focus on what they want to see, without paying attention to how to operate the DOM to implement it.
  • Vue.js and jQuery are similar in size, but Vue.js provides a more convenient development experience and easier readable code.
  • Vue.js can create modular, reusable UI components that can be combined into complex front-end applications.

What we will build

This article will build a simple online invoice using the open source template provided by Sparksuite. Hopefully this is more innovative than another to-do list and is complex enough to demonstrate the advantages of using Vue while being easy to understand.

How to Replace jQuery with Vue

We will make it interactive by providing item, unit price, and quantity inputs and automatically recalculate the "Price" column when one of the values ​​changes. We will also add a button to insert new blank rows into the invoice, as well as a "Total" field that will be automatically updated as we edit the data.

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

<tr> class="item">
  <td><input type="text" v-model="item.description" /></td>
  <td><input type="number" v-model="item.price" /></td>
  <td><input type="number" v-model="item.quantity" /></td>
  <td><pre class="brush:php;toolbar:false"><code class="javascript">$('table').on('mouseup keyup', 'input[type=number]', calculateTotals);
Copy after login
Copy after login
Copy after login
Copy after login
.00

jQuery implementation

First, let's see how to implement this function using jQuery.

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));
}
Copy after login
Copy after login
Copy after login
Copy after login

We attach the listener to the table itself, and when the "Unit Cost" or "Quantity" value changes, the calculatedTotals function will be executed:

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;
}
Copy after login
Copy after login
Copy after login
Copy after login

This function looks up all the item rows in the table and loops through them, passing each row to the calculateSubtotal function, and then adding the results. Then, insert this total into the relevant location of the invoice.

<tr> class="item">
  <td><input type="text" v-model="item.description" /></td>
  <td><input type="number" v-model="item.price" /></td>
  <td><input type="number" v-model="item.quantity" /></td>
  <td><pre class="brush:php;toolbar:false"><code class="javascript">$('table').on('mouseup keyup', 'input[type=number]', calculateTotals);
Copy after login
Copy after login
Copy after login
Copy after login
.00

In the above code, we get a reference to all input elements in the line and multiply the second and third ones to get a subtotal. Then, insert this value into the last cell in the row.

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));
}
Copy after login
Copy after login
Copy after login
Copy after login

We also have a helper function to ensure that both subtotal and total are formatted into two decimals and prefixed with currency symbols.

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;
}
Copy after login
Copy after login
Copy after login
Copy after login

Finally, we have a click handler for the "Add Row" button. What we do here is select the last project row and create a copy. The input to the cloned row is set to the default value and insert it as the new last row. We can also facilitate users and set focus to the first input so they can start typing.

The following is the complete jQuery demonstration: CodePen link

Disadvantages of jQuery

So, what's wrong with this code? Or, where can we improve it?

You may have heard of some newer libraries like Vue and React claiming to be declarative rather than imperative. Of course, looking at this jQuery code, most of the code is a list of instructions on how to operate the DOM. The purpose of each part of the code—"what"—is often difficult to distinguish through the details of "how to do it". Of course, we can clarify the intent of the code by breaking it down into well-named functions, but this code still takes some effort to re-understand after a while.

Another problem with this kind of code is that we save the application state in the DOM itself. Information about the ordering project exists only as part of the HTML that constitutes the UI. This doesn't seem like a big problem when we display information in only one location, but once we start needing to display the same data in multiple locations in the application, making sure each section remains in sync becomes increasingly complex. There is no single source of fact.

While nothing can stop us from not saving state outside of the DOM and avoiding these problems, libraries like Vue provide the functionality and structure that facilitates the creation of good architecture and write cleaner, more modular code.

Convert to Vue

So, how do we use Vue to reproduce this feature?

As I mentioned earlier, Vue does not require us to use a module packer, a translator, or select a single file component (.vue file) to get started. Like jQuery, we can simply include libraries from CDN. Let's start with replacing script tags:

function formatAsCurrency(amount) {
  return `$${Number(amount).toFixed(2)}`;
}
Copy after login
Copy after login
Copy after login

Next, we need to create a new Vue instance:

$('.btn-add-row').on('click', () => {
  const $lastRow = $('.item:last');
  const $newRow = $lastRow.clone();

  $newRow.find('input').val('');
  $newRow.find('td:last').text('<pre class="brush:php;toolbar:false"><code class="html"><🎜>
Copy after login
Copy after login
.00'); $newRow.insertAfter($lastRow); $newRow.find('input:first').focus(); });

Here we just need to provide the el option, which is a selector (just like we do with jQuery) to identify which part of the document we want Vue to manage.

We can have Vue take care of anything starting from the entire page (for example, for a single page application) or a single

. For our invoice example, we will let Vue control the HTML table.

Data

Let's also add the relevant data from three example lines to our Vue instance:

<tr> class="item">
  <td><input type="text" v-model="item.description" /></td>
  <td><input type="number" v-model="item.price" /></td>
  <td><input type="number" v-model="item.quantity" /></td>
  <td><pre class="brush:php;toolbar:false"><code class="javascript">$('table').on('mouseup keyup', 'input[type=number]', calculateTotals);
Copy after login
Copy after login
Copy after login
Copy after login
.00

data attribute is where we store the application state. This includes not only any data we want the application to use, but also information about the UI status (e.g., the currently active part of the tab group, or whether the accordion is expanded or collapsed).

Vue encourages us to separate the state of the application from its representation (i.e., the DOM) and concentrate in one place-a single source of fact.

Modify template

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

Using the v-for property, we can render a piece of HTML for each item in the items array:

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));
}
Copy after login
Copy after login
Copy after login
Copy after login

Vue will repeat this tag for each element we pass to the array (or object) constructed by v-for, allowing us to reference each element in the loop - in this case item. Since Vue is observing all properties of the data object, it will dynamically rerender the markup as the items content changes. We just need to add or delete items to the application status and Vue will be responsible for updating the UI.

We also need to add an input box so that the user can fill in the item description, unit price and quantity:

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;
}
Copy after login
Copy after login
Copy after login
Copy after login

Here, we use the v-model property to set the two-way binding between the input and the properties on the project model. This means that any changes to the input will update the corresponding properties on the project model and vice versa.

In the last cell, we use double braces {{ }} to output some text. We can use any valid JavaScript expression inside braces, so we multiply the two project properties and output the result. Similarly, since Vue is observing our data model, changes to either property will cause the expression to be automatically recalculated.

Events and methods

Now we have set up the template to render our items collection, but how do we add new lines? Since Vue will render anything in items, to render empty lines, we just need to push the object with any default value we want into the items array.

To create functions that can be accessed in the template, we need to pass them to our Vue instance as properties of the methods object:

function formatAsCurrency(amount) {
  return `$${Number(amount).toFixed(2)}`;
}
Copy after login
Copy after login
Copy after login

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

$('.btn-add-row').on('click', () => {
  const $lastRow = $('.item:last');
  const $newRow = $lastRow.clone();

  $newRow.find('input').val('');
  $newRow.find('td:last').text('<pre class="brush:php;toolbar:false"><code class="html"><🎜>
Copy after login
Copy after login
.00'); $newRow.insertAfter($lastRow); $newRow.find('input:first').focus(); });

Note that any method we create will be automatically bound to the Vue instance itself, so we can access properties and other methods in the data object as properties of this.

So, now we have a method, how do we call it when clicking the "Add Row" button? The syntax for adding event listeners to elements in a template is v-on:event-name:

const app = new Vue({
  el: 'table'
});
Copy after login

Vue also provides us with a shortcut so that we can use @ instead of v-on:, like I did in the code above. For handlers, we can specify any method in the Vue instance.

Computing properties

Now we just need to display the total at the bottom of the invoice. We can probably do this in the template itself: As I mentioned earlier, Vue allows us to place any JavaScript statement between curly braces. However, it is better to keep anything beyond the very basic logic outside the template; if we separate the logic, it is clearer and easier to test.

We can use another method for this, but I think the computed properties are more appropriate. Similar to the creation method, we pass a computed object containing functions to our Vue instance, and we want the result of these functions to be used in the template:

<tr> class="item">
  <td><input type="text" v-model="item.description" /></td>
  <td><input type="number" v-model="item.price" /></td>
  <td><input type="number" v-model="item.quantity" /></td>
  <td><pre class="brush:php;toolbar:false"><code class="javascript">$('table').on('mouseup keyup', 'input[type=number]', calculateTotals);
Copy after login
Copy after login
Copy after login
Copy after login
.00

Now we can reference this computed property in the template:

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));
}
Copy after login
Copy after login
Copy after login
Copy after login

As you may have noticed, computed properties can be treated like data; we don't have to call them in brackets. But there is another benefit to using computed properties: Vue is smart enough to cache the return value and will recalculate the function only if one of the data properties it depends on changes.

If we use methods to calculate the total, the calculation will be performed every time the template is re-rendered. Because we are using computed properties, the total will be recalculated only if the quantity or price field of the item changes.

Filter

You may have noticed a small error in our implementation. Although unit cost is an integer, our total and subtotals are not displayed when it is displayed. What we really want is to always display these numbers as two decimal places.

Rather than modifying the code that calculates subtotals and calculates totals, Vue provides us with a good way to handle common formatting tasks like this: filters.

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

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;
}
Copy after login
Copy after login
Copy after login
Copy after login

Here we create a very simple filter called currency which calls value.toFixed(2) and returns the result. We can apply it to any output in the template as follows:

function formatAsCurrency(amount) {
  return `$${Number(amount).toFixed(2)}`;
}
Copy after login
Copy after login
Copy after login

The following is the full Vue demo: CodePen link

Summary

Compare the two versions of the code side by side, and several aspects of the Vue application are prominent:

  • Clear separation between UI and the logic/data that drives it: the code is easier to understand and easier to test.
  • UI is declarative: you only need to care about what you want to see, without paying attention to how to operate the DOM to implement it.

The sizes (in KB) of the two libraries are almost the same. Of course, you can streamline jQuery with a custom build, but even for relatively simple projects like our invoice example, I think the ease of development and the readability of the code justifies this difference.

Vue can do a lot of things that we haven't introduced here. Its advantage is that it allows you to create modular, reusable UI components that can be combined into complex frontend applications. If you are interested in getting to know Vue in depth, I suggest you check out Getting Up and Running with the Vue.js 2.0 Framework.

FAQs about replacing jQuery with Vue

What is the main difference between jQuery and Vue.js?

jQuery is a fast, compact and feature-rich JavaScript library. It makes HTML document traversal and manipulation, event processing, and animations easier, and its easy-to-use API can run in a variety of browsers. Vue.js, on the other hand, is a progressive JavaScript framework for building user interfaces. Unlike other overall frameworks, Vue's design has incremental adoptability from the very beginning. The core library focuses only on view layers, is easy to get started and integrates 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 provides a more modern and comprehensive way to build web applications. Vue.js is component-based, which promotes reusability and maintainability. It also has a stronger ecosystem with tools such as state management, routing, etc. Additionally, Vue.js has a virtual DOM that can improve performance in some cases.

How to convert jQuery code to Vue.js?

Converting jQuery code to Vue.js requires understanding of the equivalent Vue.js methods and properties of jQuery functions. For example, you will use Vue's mounted() lifecycle hook instead of jQuery's $(document).ready(). Similarly, you will use Vue's axios or fetch instead of jQuery's $.ajax() for HTTP requests.

Can I use jQuery and Vue.js in one project?

While technically can use both jQuery and Vue.js, this is not usually recommended. Mixing the two can lead to code confusion and potential conflicts, as both libraries try to manage the DOM on their own terms. It is best to use one of them completely.

How to handle events in Vue.js, compared to jQuery?

In jQuery, you usually attach an event listener to an element using methods such as .click(), .on(), or .bind(). In Vue.js, you use the v-on directive (or its abbreviation @) to listen for DOM events and run some JavaScript when triggered.

How does data binding in Vue.js work compared to jQuery?

jQuery does not have built-in data binding. You manually select an element and update its contents. On the contrary, Vue.js has a powerful data binding system. You can use the v-model directive to create two-way data bindings on form input, textarea, and select elements.

How to animate elements in Vue.js, compared to jQuery?

jQuery has built-in animation methods, such as .fadeIn(), .slideUp(), etc. Vue.js, on the other hand, provides conversion components that allow greater flexibility when animate elements into and out of the DOM.

How to make HTTP requests in Vue.js, compared to jQuery?

In jQuery, you usually use the $.ajax() method to make HTTP requests. Vue.js does not have this method built in, but you can use libraries like modern APIs (like fetch) or axios to make HTTP requests.

How does Vue.js handle reactiveness, compared to jQuery?

jQuery does not have a built-in reactive system. When your data changes, you manually update the DOM. Vue.js, on the other hand, has a reactive data system. The view is automatically updated when you change the data.

How to replace jQuery plugin with Vue.js component?

Many jQuery plugins can be replaced with Vue.js components. Vue.js has a rich ecosystem that provides thousands of open source components available. You can also create your own custom components. This improves the reusability and maintainability of the code.

Please note that I have rewritten the output according to your requirements and retained the original format and location of all pictures. Since I don't have access to CodePen, I can't provide the actual CodePen link, please create and replace the "[CodePen link]" placeholder yourself.

The above is the detailed content of How to Replace jQuery with Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles