How to use JQuery in Vue Component

How can I use or integrate a JQuery function to my vue component? I just want to use it in this one component.
I work with webpack.

The function in JQuery:

 var focus=0

$("body").keydown(function(e){
// left arrow
if ((e.keyCode || e.which) == 37)
{   
  focus=focus-1;
    if (focus<1)
      {
        focus=7
      }
  document.getElementById("Button"+focus).focus();
}
// right arrow
if ((e.keyCode || e.which) == 39)
{
    focus=focus+1;  
    if (focus>7)
      {
        focus=1
      }
    document.getElementById("Button"+focus).focus();
}   

});

Good morning sir,

You could add your JQuery code inside your mounted event inside your component like so:

mounted () {
   // Your JQuery code here
}

Hope that helps.

4 Likes

I did it but “$” is not defined. What is to do to solve this?

You’re getting this error from ESLint or the browser?
Did you correctly import JQuery?

If you have installed JQuery through npm, you could do this:

import JQuery from 'jquery'
window.$ = JQuery

or simply

import $ from 'jquery'
5 Likes

“$” is an ESLint error.
The import of JQuery is failed:

ChromeDriver installation failed Error with http(s) request: Error: unable to verify the first certificate
npm WARN url-loader@1.1.1 requires a peer of webpack@^4.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {“os”:“darwin”,“arch”:“any”} (current: {“os”:“win32”,“arch”:“x64”})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! chromedriver@2.41.0 install: node install.js
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the chromedriver@2.41.0 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

I don`t know what to do or is there another way to import JQuery?
I use: npm install jquery --save and get this error

Of course, you could just import manually jQuery in the classic way by putting the script in your html file.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

By doing that, you will automatically import jQuery and, as far I know, you will have $ available.

But if you insist to install through npm, see https://www.npmjs.com/package/jquery for detailled explanation on how to install & use jQuery.

Thanks for good help. Now is works.

if it’s just for the code you wrote it’s exaggerated to include all jQuery, rewrite the association of the keydown event, the rest is already all javascript.

https://developer.mozilla.org/en-US/docs/Web/Events/keydown

@WilliamDASILVA I have installed jquery and import to vue file like this. But jquery inside the mounted function not working. my vue version is 2.6 , what could be the reason for this issue?

It works for me, thanks

thank you.

It works for me. Thank you.