search
HomeWeb Front-endCSS TutorialMaking the Move from jQuery to Vue

Making the Move from jQuery to Vue

Developers who have been using jQuery for a long time and have recently turned to Vue may be interested in the migration process of both.

First of all, I need to be clear, I do not recommend that you give up jQuery. Although this statement is popular now, I wrote a similar article myself a few years ago (“How do I (not) use jQuery”). If jQuery can meet your needs and your end users can use your website smoothly, then continue to use it.

This guide is mainly for developers who have many years of experience using jQuery and want to learn how to accomplish the same tasks in Vue. So I'll focus on what I think is the "core" use case of jQuery. I wouldn't cover all possible features, but instead take the "I often do [X] with jQuery" approach, which might be more resonant for those who are considering learning Vue. (By the way, also note that the way I write the examples is just a way to accomplish the task. Both jQuery and Vue offer multiple ways to achieve the same goal, which is a good thing!)

So let's consider some advanced tasks that we might turn to jQuery:

  • Find elements in the DOM (to operate on them later)
  • Change content in the DOM (for example, the text of a paragraph or the class of a button)
  • Read and set form values
  • Form verification (actually just a combination of the above)
  • Ajax call and processing results
  • Event handling (for example, perform an action when a button is clicked)
  • Measure or change the style of an element

Of course, jQuery has much more than that, but these uses (at least in my opinion) cover the most common use cases. Also note that there are many cross-correlations in the above list. So, should we start by comparing each feature one by one? No, don't worry. Let's first introduce the main differences of Vue applications.

Define the "scope of action" of Vue

When we add jQuery to the page, we are actually adding a Swiss Army knife to our JavaScript code to handle common web development tasks. We can execute any use case in any order we think is appropriate. For example, a customer may need form verification today and then, in about a month, ask to add an Ajax-based search form to the header of the website.

Vue has a significant difference in this regard. When starting a Vue project, we first define the "region" we want to focus on in the DOM. So let's consider a simple prototype webpage:

<header>
  Fancy header content</header>
<div id="sidebar">
  Some sidebar content</div>

<main>
  <p id="main-content">
    Main website content, very important content...
  </p>
  <div id="loginForm">
    Of course there is also a login form</div>
</main>

In a typical jQuery application, we might write code to handle headers, sidebars, login forms, etc. No big deal:

 $(document).ready(function() {

  $('header') // Do something...

  $('#sidebar') // Do something...

  $('#loginForm') // Do something...

});

In the Vue application, we first specify what to process. Suppose our client first asks to add validation to the loginForm element. Our Vue code will specify this:

 new Vue({
  el: '#loginForm',
  // The code is here...
});

This means that if the customer later decides to add something to the sidebar, we usually add a second Vue application:

 new Vue({
  el: '#loginForm',
  // The code is here...
});

new Vue({
  el: '#sidebar',
  // The code is here...
});

Is this a bad thing? Absolutely not. We immediately gained the benefits of packaging. If we accidentally use variables with common names (we all did), we don't have to worry about conflicting with other parts of the code. When a customer later adds another request, separate our unique, logical set of Vue codes like this, so that we can rest assured that they will interfere with each other.

So, this is a good thing. But when I first started using Vue it did give me a pause. Now, let's look at our use cases.

Find elements in DOM

Another interesting or scary aspect you will find is how to "find elements in the DOM". This is a bit vague, but let's consider a specific example. We have a button and when clicked, we make something happen. Here is a simplified example:

 <button id="myButton">Click me!</button>
 $(document).ready(function() {

  $('#myButton').click(function() {
    alert(1);
  });

});

Now let's compare it to how Vue implements:

<div id="app">
  <button>Click me!</button>
</div>
const app = new Vue({
  el: '#app',
  methods: {
    doSomething: function() {
      alert(1);
    }
  }
});

Vue applications are verbose, but be aware of how to directly connect operations ("click") between tags and the functions to be called. Vue's code has no association with the DOM (except the el part, where we define where it needs to work). It's easily one of the things that convinced me the most about Vue - it's easier to understand what's going on. Also, I don't have to worry too much about the ID value and selector. If I change the class or ID of the button, I don't need to go back to my code and worry about updating the selector.

Let's consider another example: Finding and changing text in the DOM. Imagine that after clicking the button, the text of another part of the DOM will now be changed.

 <button id="myButton">Click me!</button>
$(document).ready(function() {

  $('#myButton').click(function() {
    $('#result').text('You clicked me, thank you!');
  });

});

I added a new span, and now when the button is clicked we use another selector to find it and use the jQuery utility method to change the text inside it. Now consider the Vue version:

<div id="app">
  <button>Click me!</button>
  <span>{{ resultText }}</span>
</div>
const app = new Vue({
  el: '#app',
  data: {
    resultText: ''
  },
  methods: {
    doSomething: function() {
      this.resultText = 'You clicked me, thank you! ';
    }
  }
});

In this example, we use Vue's template language (highlighted lines) to specify that we want to render a variable inside the span, in this case resultText. Now, when the button is clicked, we change the value and the internal text of the span will change automatically.

By the way, Vue supports the abbreviation of the v-on attribute, so the buttons in the example can be replaced by @click="doSomething".

Read and write form variables

Processing forms is probably one of the most common and useful things we can do with JavaScript. Even before JavaScript, most of my early "web development" was writing Perl scripts to handle form submissions. As a primary way to accept user input, forms have been critical to the web and may still be the case for quite some time. Let's consider a simple jQuery example that reads some form fields and sets another field:


=
$(document).ready(function() {
  let $first = $('#first');
  let $second = $('#second');
  let $sum = $('#sum');
  let $button = $('#sumButton');

  $button.on('click', function(e) {
    e.preventDefault();
    let total = parseInt($first.val(), 10) parseInt($second.val(), 10);
    $sum.val(total);
  });
});

This code demonstrates how jQuery reads and writes through the val() method. We end up taking four items (all three form fields and buttons) from the DOM and using simple math operations to generate the results. Now consider the Vue version:


=
new Vue({
  el: '#myForm',
  data: {
    first: 0,
    second: 0,
    sum: 0
  },
  methods: {
    doSum: function() {
      this.sum = this.first this.second;
    }
  }
})

This introduces some interesting Vue shortcuts. First, v-model is how Vue creates bidirectional data binding between values ​​in DOM and JavaScript. Data block variables will be automatically synchronized with the form field. Change the data and the form will be updated. Change the form and the data will be updated. .number is a flag that instructs Vue to treat inherited string values ​​of a form field as numbers. If we omit it and do the addition operation, we will see string addition instead of arithmetic operation. I've been using JavaScript for nearly a century and still messing up this.

Another clever "skill" is @click.prevent. First, @click defines the button's click handler, and then the .prevent partly prevents the browser from submitting the form's default behavior (equivalent to event.preventDefault()).

The last point is the addition of the doSum method bound to the button. Note that it just uses data variables (Vue is provided in this scope).

While this is mostly my personal feeling, I really like the lack of query selectors in scripts when written in Vue and how HTML can make it clearer what it is doing.

Finally, we can even get rid of the button completely:


=
new Vue({
  el: '#myForm',
  data: {
    first: 0,
    second: 0
  },
  computed: {
    sum: function() {
      return this.first this.second;
    }
  }
})

A cooler feature of Vue is the computed properties. They are dummies that identify when their derived values ​​are updated. In the above code, sum will be updated as soon as any of the two form fields changes. This works outside of form fields. We can render the sum like this:

 The total is {{sum}}.

Using Ajax

How easy it is to make using Ajax, which is commendable. In fact, I can say that I've used Ajax in the "native" way probably only once in total. (If you are curious, you can look at the specification of XMLHttpRequest and may be glad you avoided it yourself.) jQuery's simple $.get(...) method works in many cases, and $.ajax() also makes it easy when something more complex is needed. Another thing that jQuery does well is the way it handles JSONP requests. Although most JSONP is not required now using CORS, JSONP is a way to handle requests to APIs on different domains.

So, what has Vue done for you to make Ajax easier? Nothing!

OK, this sounds horrible, but it is not. There are many options available to handle HTTP requests, and Vue.js takes a more agnostic approach that lets us developers decide for themselves how to handle it. So yes, it does mean more work, but we have some great options.

The first thing to consider is Axios, a Promise-based library that is very popular in the Vue community. Here is a simple example of it in action (taken from its readme):

 axios.get('/user?ID=12345')
  .then(function (response) {
    // Console.log(response);
  })
  .catch(function (error) {
    // Handle error console.log(error);
  })
  .then(function () {
    // Always execute});

Axios certainly supports POST requests and lets specify headers as well as many other options.

While Axios is very popular among Vue developers, I don't really like it. (At least not yet.) Instead, I prefer Fetch. Fetch is not an external library, but a standard web way of performing HTTP requests. Fetch is well supported in about 90% of browsers, but that means it is not completely safe, but we can always use polyfill if needed.

While this is completely beyond the scope of what we are discussing here, Kingsley Silas has written an excellent guide on using Axios and Fetch with React.

Like Axios, Fetch is also based on Promise and has a friendly API:

 fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(JSON.stringify(myJson));
  });

Both Axios and Fetch cover all types of HTTP requests, so either one is suitable for any number of needs. Let's look at a simple comparison. This is a simple jQuery demonstration using the Star Wars API.

<h1 id="Star-Wars-movies"> Star Wars movies</h1>
    $(document).ready(function() {
      $.get('https://swapi.com/api/films', function(res) {
        let list = '';
        result.results.forEach(function(r) {
          list = `
  • ${r.title}
  • `; }); $('#films').html(list); }); });

    In the example above, I use $.get to access the API and return to the movie list. I then use that data to generate a list of titles as li tag elements and insert them all into the ul block.

    Now, let's consider an example using Vue:

    <div id="app">
      <h1 id="Star-Wars-movies">Star Wars movies</h1>
      <ul><li v-for="film in films">{{ film.title }}</li></ul>
    </div>
    const app = new Vue({
      el: '#app',
      data: {
        films: []
      },
      created() {
        fetch('https://swapi.com/api/films')
          .then(res => res.json())
          .then(res => {
            this.films = result.results;
          });
      }
    })

    This best part is probably the use of v-for templates. Note that Vue doesn't care about layout (at least JavaScript). The data is taken from the API. It is assigned a variable. The layout is responsible for displaying it. I've always hated using HTML in my JavaScript, and while jQuery has solutions to this problem, baking it into Vue makes it a natural choice.

    A complete (although a bit trivial) example

    For a deeper understanding, let's consider a more realistic example. Our customers asked us to build a high-level, Ajax-enabled front-end search interface for the product API. The function list includes:

    • Supports filtering by name and product category
    • Form verification, requiring us to provide search terms or categories
    • When the API is accessing, display a message to the user and disable the submit button
    • Once completed, the processing report does not show any products or matches are listed

    Let's start with the jQuery version. First is HTML:

    
    

    There is a form with our two filters and two divs. One is used as a temporary state when searching or reporting an error, and the other is used to render the result. Now, check the code.

     // ... (The code is too long, omitted here) ...

    The code first creates a set of variables for each DOM project we want to use—form fields, buttons, and divs. The core of the logic is located in the button's click handler. We verify and if everything works, then POST requests to the API. When it returns, if there are no matches, we either render the result or display the message.

    Now let's consider the Vue version. Again, let's start with the layout:

    <div id="app">
      <form>
        <p>
          <label for="search">search</label>
          <input type="text" v-model="search" id="search">
        </p>
        <p>
          <label for="category">category</label>
          <select v-model="category" id="category">
            <option value="">all</option>
            <option value="Food">food</option>
            <option value="Games">game</option>
          </select>
        </p>
        <button :disabled="searchBtnDisabled">search</button>
      </form>
    
      <div v-html="status"></div>
      <ul v-if="results"><li v-for="result in results">{{ result.name }}</li></ul>
    </div>

    Starting from the top, changes include:

    • Wrap the layout in a div so that Vue knows where to work.
    • Use v-model for form fields to easily process data.
    • Use @click.prevent to handle the main search operations.
    • Use :disabled to bind the button's disabled state to a value in the Vue application (we'll see what it does later).
    • The status value is slightly different from the previous example. While jQuery has a specific method to set text in a DOM project and another method for HTML, Vue needs to use v-html when assigning HTML to the value to be rendered. If we try to use {{status}} with HTML, the tag will be escaped.
    • Finally, the iteration is processed using v-if conditionally rendered with v-for.

    Now let's look at the code.

     // ... (The code is too long, omitted here) ...

    The first code block worth mentioning is a set of data fields. Some map to form fields, while others map to results, status messages, etc. The searchProducts method handles most of the same things as in the jQuery version, but in general, there is much less code directly bound to the DOM. For example, even if we know the results are listed in an unordered list, the code itself doesn't care about this. It simply assigns the value, and the tag is responsible for rendering it. Overall, JavaScript code focuses more on logic than jQuery code, which "feels" better separation of concerns.

    jQuery is gone, Vue lasts forever!

    OK, that's a bit exaggerated. As I said at the beginning, if you like to use jQuery and it works for you, I absolutely don't think you should change anything.

    However, I can say that Vue feels like a good "next step" for people who are used to using jQuery. Vue supports complex applications and has powerful command-line tools for scaffolding and building projects. But for simpler tasks, Vue has become my go-to development tool as a good "modern jQuery" alternative!

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

    Statement
    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
    Next Level CSS Styling for CursorsNext Level CSS Styling for CursorsApr 23, 2025 am 11:04 AM

    Custom cursors with CSS are great, but we can take things to the next level with JavaScript. Using JavaScript, we can transition between cursor states, place dynamic text within the cursor, apply complex animations, and apply filters.

    Worlds Collide: Keyframe Collision Detection Using Style QueriesWorlds Collide: Keyframe Collision Detection Using Style QueriesApr 23, 2025 am 10:42 AM

    Interactive CSS animations with elements ricocheting off each other seem more plausible in 2025. While it’s unnecessary to implement Pong in CSS, the increasing flexibility and power of CSS reinforce Lee's suspicion that one day it will be a

    Using CSS backdrop-filter for UI EffectsUsing CSS backdrop-filter for UI EffectsApr 23, 2025 am 10:20 AM

    Tips and tricks on utilizing the CSS backdrop-filter property to style user interfaces. You’ll learn how to layer backdrop filters among multiple elements, and integrate them with other CSS graphical effects to create elaborate designs.

    SMIL on?SMIL on?Apr 23, 2025 am 09:57 AM

    Well, it turns out that SVG's built-in animation features were never deprecated as planned. Sure, CSS and JavaScript are more than capable of carrying the load, but it's good to know that SMIL is not dead in the water as previously

    'Pretty' is in the eye of the beholder'Pretty' is in the eye of the beholderApr 23, 2025 am 09:40 AM

    Yay, let's jump for text-wrap: pretty landing in Safari Technology Preview! But beware that it's different from how it works in Chromium browsers.

    CSS-Tricks Chronicles XLIIICSS-Tricks Chronicles XLIIIApr 23, 2025 am 09:35 AM

    This CSS-Tricks update highlights significant progress in the Almanac, recent podcast appearances, a new CSS counters guide, and the addition of several new authors contributing valuable content.

    Tailwind's @apply Feature is Better Than it SoundsTailwind's @apply Feature is Better Than it SoundsApr 23, 2025 am 09:23 AM

    Most of the time, people showcase Tailwind's @apply feature with one of Tailwind's single-property utilities (which changes a single CSS declaration). When showcased this way, @apply doesn't sound promising at all. So obvio

    Feeling Like I Have No Release: A Journey Towards Sane DeploymentsFeeling Like I Have No Release: A Journey Towards Sane DeploymentsApr 23, 2025 am 09:19 AM

    Deploying like an idiot comes down to a mismatch between the tools you use to deploy and the reward in complexity reduced versus complexity added.

    See all articles

    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

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment