将Jquery添加到Vue-Cli 3 [英] Add Jquery to Vue-Cli 3

查看:99
本文介绍了将Jquery添加到Vue-Cli 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently trying to add Jquery to my vue-cli project. I am aware of the missbehaviour it can produce, but anyway; Since there is no build/webpack.base.conf.js anymore I tried editing vue.config.js by adding:

 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仍未定义.

Both options don't seem to work. With #1 nothing seems to happen, with #2 I get the compile error; "plugins" is not allowed or 'ProvidePlugin' is unresolved and when I try to import jQuery directly in main.js and define the $ operator, jquery stays undefinded when I try to use it.

非常感谢您!

推荐答案

通过添加到main.js

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

为我做到了,现在jQuery在全球范围内可用.

That did it for me and jQuery is now available globally.

另一种方法是;

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

我希望这将有助于将来有人遇到相同的问题.如果仍然无法解决,请查看此问题,或查看

I hope this will help someone stumbling over the same problem in the future. If you still can't figure it out, check this question or have a look at the documentation.

编辑:确保您已运行npm install jquery.

这篇关于将Jquery添加到Vue-Cli 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆