using jquery in vue js in Laravel 5.7

£可爱£侵袭症+ 提交于 2020-08-20 05:20:54

问题


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


回答1:


You need to import it in app.js file as

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



回答2:


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>



回答3:


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



来源:https://stackoverflow.com/questions/55236526/using-jquery-in-vue-js-in-laravel-5-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!