繁体   English   中英

在 Laravel 5.7 的 vue js 中使用 jquery

[英]using jquery in vue js in Laravel 5.7

我对jquery的安装和使用步骤有点困惑。 Jquery 已经在 package.json 中

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

我的 laravel-mix 如下所示。

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

和 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
});

索引.vue

<script>

import JQuery from 'jquery';
let $ = JQuery

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

export default {

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

我不确定,我是否在这里遗漏了什么。 另外关于 vue 模板中的 Jquery 用法:在我的Index.vue ,我是否只需要在<template>之后打开另一个脚本标记并在那里编写 jquery 代码? 还是在 vue 中写法不同? 因为我的 jquery 代码在Index.vueIndex.vue

您需要将其导入 app.js 文件中

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

默认情况下 jQuery 已经在 bootstrap.js 中加载和初始化

引导程序.js

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

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

所以你可以在 Vue 组件的方法、mounted、created 等中使用 jQuery...但你不能在里面使用它

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

但是如果你想在模板标签中使用 jquery ($)。 那么你必须在 app.js 中添加这些行

应用程序.js

require('./bootstrap');

window.Vue = require('vue');

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

然后你可以在模板标签内使用 $ 。

例子:

AnyVueComponent.vue

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

从加载 app.js 的 layouts/app.blade.php 中的脚本标签中删除 defer 关键字

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM