[英]Add Jquery to 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
})
}
...
}
或者
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 保持未定义状态。
非常感谢您提前!
通过添加到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
}
});
我希望这会帮助将来遇到同样问题的人。 如果您仍然无法弄清楚,请检查此问题或查看文档。
编辑:确保您运行npm install jquery
。
#2 你忘记在 vue.config.js 中添加configureWebpack
const webpack = require('webpack')
module.exports = {
configureWebpack: {
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jquery: 'jquery',
'window.jQuery': 'jquery',
jQuery: 'jquery'
})
]
},
}
我通过以下步骤做到了:
首先安装jquery
npm install jquery --save-dev
在任何组件或视图中:
<script>
import jQuery from "jquery";
const $ = jQuery;
window.$ = $;
....
....
....
或如上答案,两者都是相同的:
window.$ = window.jQuery = require("jquery");
现在您可以在页面的任何位置使用,为了全球可用性,只需按照上述答案进行操作。
在 vue.config.js 中添加以下内容
chainWebpack: (config) => {
config
.plugin('provide')
// eslint-disable-next-line global-require
.use(require('webpack').ProvidePlugin, [{
'window.Quill': 'quill/dist/quill.js',
Quill: 'quill/dist/quill.js',
'window.jQuery': 'jquery/src/jquery.js',
jQuery: 'jquery/src/jquery.js',
}]);
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.