将Jquery添加到Vue-Cli 3

问题描述 投票:4回答: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
    })
  }
   ...
 }

要么

const webpack = require('webpack')

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

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

非常感谢你提前!

javascript jquery vue.js vue-cli-3
3个回答
10
投票

通过添加到main.js来解决它:

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

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

Vue.use({
install: function(Vue, options){
    Vue.prototype.$jQuery = require('jquery'); // you'll have this.$jQuery anywhere in your vue project
}

})

我希望这将有助于将来绊倒同一问题的人。如果你仍然无法弄明白,请查看this question或查看the documentation

编辑:菲利普说,确保你以前跑过npm install jquery


5
投票

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

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

0
投票

我按照以下步骤做到了:

首先安装jquery

npm install jquery --save-dev

在任何组件或视图中:

<script>

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

....
....
....

或者如上所述,两者都是相同的:

window.$ = window.jQuery = require("jquery");

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

© www.soinside.com 2019 - 2024. All rights reserved.