3

I am a bit confused about steps of jquery installation and usage. Jquery is already in package.json

"devDependencies": {
        "jquery": "^3.2",
        "laravel-mix": "^4.0.7",

And my laravel-mix looks like below.

mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css');

And App.js

require('./bootstrap');
require('./jquery');

window.Vue = require('vue');

Vue.component('index-content', require('./components/Index.vue').default)


const app = new Vue({
    el: '#app',
    // router
});

Index.vue

<script>

import JQuery from 'jquery';
let $ = JQuery

$("#btn").click(function(){
  $("#hello").toggle();
});

export default {

  data() {
    ...
    ...
  }
}
</script>

I am not sure, am I missing something here or not. Additionally about the Jquery usage in vue template: in my Index.vue do I just need to open another script tag after <template> and write jquery code there? or in vue writing is different? Because my jquery code is not working in Index.vue

3
  • Why are you trying to use jquery with vue? They don't mix well and you shouldn't use jquery with vue. Your example with toggling should be rewritten using vue, not by cramming bad jquery stuff into <script> block.
    – Mjh
    Commented Mar 19, 2019 at 8:57
  • I am just writing that toggle for an example. of course I know I can do that in vue too. And about the reason: I am not very familiar with vue. So I am trying to include jquery library too.. @Mjh
    – user10753862
    Commented Mar 19, 2019 at 8:59
  • Hey man try registering your component inside new Vue({}); Commented May 2, 2021 at 22:10

3 Answers 3

2

You need to import it in app.js file as

window.$ = require('jquery')
window.JQuery = require('jquery')
1
  • and this is it what about using in template? I mean do I need to open second script tag or... ?
    – user10753862
    Commented Mar 19, 2019 at 8:41
1

by default jQuery already loaded and initialized in bootstrap.js

bootstrap.js

try {
    window.Popper = require('popper.js').default;
    window.$ = window.jQuery = require('jquery');

    require('bootstrap');
} catch (e) {}

So you can use jQuery in Vue component's methods, mounted, created, etc... but you can not use this inside of

<template>
// your code is here
</template>

but if you want to use jquery ($) inside the template tag. then you have to add those line in app.js

App.js

require('./bootstrap');

window.Vue = require('vue');

// below above code
Vue.prototype.$ = $;

Then you can use $ inside of template tag.

Example:

AnyVueComponent.vue

<template>
   <div class="container">
       <div class="test">
          <h1>Text inside of .test class</h1>
          {{ $(".test").css({
          backgroundColor: 'red'
          }) }}
        </div>
   </div>
</template>
1

remove defer keyword from your script tag in layouts/app.blade.php which loads app.js