hjortur17's avatar

Use jQuery with Vue

Hi, what is the best way to import jQuery from NPM with Laravel. I'm not using jQuery anywhere else other then in one component. I tried to to

import $ from 'jquery';

in the component but that didn't work. Any ideas how to get it to work? Because I'm trying to use

$.getJson

in my VueComponent but I only get this error

$.getJson is not a function

0 likes
6 replies
Cronix's avatar

laravel loads it like

try {
    window.$ = window.jQuery = require('jquery');
} catch (e) {}

and just attaches it to the global window object.

1 like
grenadecx's avatar

In a default laravel installation they do it like this:

window.$ = window.jQuery = require('jquery');

Wouldn't you be able to do the same?

hjortur17's avatar

I have tried to add this lines to my component (they didn't work)

import JQuery from 'jquery'
let $ = JQuery

and this lines to bootstrap.js file

window.$ = require('jquery')
window.JQuery = require('jquery')
Cronix's avatar
Cronix
Best Answer
Level 67

You should just need

window.$ = window.jQuery = require('jquery')

$ and jQuery are now global. Just use them in your Vue code.

let data = $('#something');
// let data = jQuery('#something');

If "its not working," show how you're using jquery inside Vue.

If you can go to your browsers console and just type $ and enter, and it shows a function instead of an error, then jquery is loaded and it's your use of it in Vue that is not correct.

2 likes
hjortur17's avatar

I figured it out, thanks. So when I did it like this

window.$ = window.jQuery = require('jquery')

in my bootstrap.js file and then typed $ in my console, I saw that the function I'm trying to use is called getJSON not getJson.

Thanks everybody!

Please or to participate in this conversation.