将Jquery添加到Vue-Cli 3

non*_*oat 7 javascript jquery vue.js vue-cli-3

我目前正在尝试将Jquery添加到我的vue-cli项目中.我知道它可以产生的错误行为,但无论如何; 由于没有build/webpack.base.conf.js了,我尝试vue.config.js通过添加以下内容进行编辑:

 module.exports {
    ...
    chainWebpack: config => {
    config.plugin('define').tap(definitions => {
      definitions[0] = Object.assign(definitions[0], {
        $: 'jquery',
        jquery: 'jquery',
        'window.jQuery': 'jquery',
        jQuery: 'jquery',
        _: 'lodash'
      })
      return definitions
    })
  }
   ...
 }
Run Code Online (Sandbox Code Playgroud)

要么

const webpack = require('webpack')

module.exports {
   ...
 plugins: [
  new webpack.ProvidePlugin({
     $: 'jquery',
     jquery: 'jquery',
     'window.jQuery': 'jquery',
     jQuery: 'jquery'
   })
  ]
   ...
 }
Run Code Online (Sandbox Code Playgroud)

这两个选项似乎都不起作用.#1似乎没有任何事情发生,#2我得到了编译错误; "插件"是不允许的,或者"ProvidePlugin"未解析,当我尝试直接在main.js中导入jQuery并定义$运算符时,jquery在我尝试使用它时保持未定义状态.

非常感谢你提前!

non*_*oat 16

解决它简单添加到main.js:

npm install jquery

这样做对我而言,jQuery现在可以在全球范围内使用.另一种方法是;

window.$ = window.jQuery = require('jquery');
Run Code Online (Sandbox Code Playgroud)

})

我希望这将有助于将来绊倒同一问题的人.如果您仍然无法弄清楚,请查看此问题或查看文档.


小智 8

#2您忘记将configureWebpack添加到vue.config.js中

const webpack = require('webpack')
module.exports = {
  configureWebpack: {
    plugins: [
      new webpack.ProvidePlugin({
        $: 'jquery',
        jquery: 'jquery',
        'window.jQuery': 'jquery',
        jQuery: 'jquery'
      })
    ]
  },
}
Run Code Online (Sandbox Code Playgroud)


Ari*_*afa 5

我通过以下步骤做到了:

首先安装jquery

npm install jquery --save-dev
Run Code Online (Sandbox Code Playgroud)

在任何组件或视图中:

<script>

import jQuery from "jquery";
const $ = jQuery;
window.$ = $;

....
....
....
Run Code Online (Sandbox Code Playgroud)

或如上答案,两者都是相同的:

window.$ = window.jQuery = require("jquery");
Run Code Online (Sandbox Code Playgroud)

现在您可以在页面的任何位置使用,为了全球可用性,只需按照上述答案进行操作。