【问题标题】:How to import a jquery plugin in a vuecli3 project如何在 vuecli3 项目中导入 jquery 插件
【发布时间】:2019-11-19 20:51:19
【问题描述】:

我正在尝试将 jquery 插件导入到我的项目中。 我不断收到以下错误。

未捕获的引用错误:$ 未定义

jquery 插件不是通过 npm 添加的,所以我可以假设这可能是导致问题的原因。

Jquery 本身是通过 npm 导入和安装的。我确实测试过它是否有效。

我使用 Vuecli3 创建了一个项目 然后我设法通过 npm 导入和安装 jquery。

然后我为我的 jquery 代码创建了一个目录 /js/slick.js,其中文件被导入但文件未检测到 jquery。

这行得通。

app.vue


    export default {
        mounted() {
            $("body").html("This is Hello World by JQuery");
        }

    }

main.js


    import Vue from 'vue'
    import App from './App.vue'
    window.$ = window.jQuery = require('jquery');

    new Vue({
      render: h => h(App),
    }).$mount('#app')

以下内容不起作用,即使它拾取/检测文件。 (我也尝试在本地加载 jquery) (slick.js 只是一个简单的 hello world)


<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

    require("../js/slick.js");
    import slick from '../js/slick.js';
    export default {


    }

在整个项目设置场景中我还是新手。

但我想也许我应该将它添加到 package.json 中的依赖项中


      "dependencies": {
        "core-js": "^2.6.5",
        "jquery": "^3.4.1",
        "vue": "^2.6.10",
        "vue-draggable-resizable": "^2.0.0-rc2",
        "slick": "./js/slick.js"
      },

没有任何区别。

js 控制台错误

slick.js?a016:1 Uncaught ReferenceError: $ is not defined
    at eval (slick.js?a016:1)
    at Object../src/js/slick.js (app.js:2270)
    at __webpack_require__ (app.js:724)
    at fn (app.js:101)
    at eval (cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/Item.vue?vue&type=script&lang=js&:2)
    at Module../node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/Item.vue?vue&type=script&lang=js& (app.js:840)
    at __webpack_require__ (app.js:724)
    at fn (app.js:101)
    at eval (Item.vue?12bc:1)
    at Module../src/components/Item.vue?vue&type=script&lang=js& (app.js:2247)

【问题讨论】:

    标签: jquery vue.js jquery-plugins


    【解决方案1】:

    在你的终端中进入你的项目目录并写入

    npm install jquery
    

    在你的 App.vue 中写

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

    【讨论】:

    • 我确实尝试过。我仍然收到 Uncaught ReferenceError: $ is not defined
    • @Fanna1119 我已经更新了我的答案,你想试试吗?
    • 还是不行。 :( 并且因为它在挂载中工作(如 sn-p 所示),所以它不适用于基本导入是没有意义的。它是否与一个文件相关,可能在另一个文件之前加载?
    猜你喜欢
    • 2014-10-08
    • 2016-01-06
    • 2017-07-01
    • 2014-06-03
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多