How to use jquery in Vue.js?

by jeanie_reilly , in category: JavaScript , 2 years ago

How to use jquery in Vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@jeanie_reilly You can install jQuery library via npm install jquery first and then import jQuery library into your Vue.js project, here is code as example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<script setup>
import $ from 'jquery';

const handleClick = () => {
  // Use jQuery
  $('button').css('background-color', 'red');
}
</script>

<template>
  <h1>How to use jquery in Vue.js?</h1>
  <button @click="handleClick">Button</button>
</template>

Member

by alana , 10 months ago

@jeanie_reilly 

To use jQuery in Vue.js, follow these steps:

  1. Install jQuery in your project using npm or yarn.
1
npm install jquery --save


or

1
yarn add jquery


  1. Import jQuery in your Vue component using import statement.
1
import $ from 'jquery';


  1. Use jQuery in Vue component methods or lifecycle hooks.
1
2
3
4
5
6
7
8
export default {
  created() {
    // jQuery code here
    $("button").click(function(){
      alert("Hello world!");
    });
  }
}


Note: While it's possible to use jQuery in Vue.js, it's not recommended since Vue.js has its own way of manipulating the DOM. Using jQuery can lead to conflicts and unexpected behavior. It's better to use Vue.js built-in methods such as directives, computed properties, and methods to manipulate the DOM.