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

查看:37
本文介绍了将 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天全站免登陆