npm install jquery --save-dev
Open file build/webpack.base.conf.js
and add plugins
:
module.exports = { plugins: [ new webpack.ProvidePlugin({ $: 'jquery', jquery: 'jquery', 'window.jQuery': 'jquery', jQuery: 'jquery' }) ] ... }
Also at top of file add:
const webpack = require('webpack')
If you are using ESLint
, open .eslintrc.js
and add next globals: {
module.exports = { globals: { "$": true, "jQuery": true }, ...
Now you are ready to go. Use $
anywhere in your js.
搞一个文件测试一下 jQuery 是否可用
新建 /src/page/jq.vue
文件,录入下面的内容
<template>
<div class="love">
<p>这里是初始文字</p>
<button @click="testJQ">看看 jquery 有没有工作</button>
</div>
</template>
<script>
export default {
methods: {
testJQ () {
$('.love p').html('jquery 工作正常!')
}
}
}
</script>
去掉 eslint 报错 ‘$’ is not defined
虽然引用了 jQuery
但是你真正去写的时候,会报这个错误。我们首先需要关闭掉这个错误。
关闭有两种方法,一种是临时关闭,一种是永久关闭。我这里提供永久关闭的方法。
我们编辑 /.eslintrc.js
文件
env: {
browser: true,
jquery: true
},
- 1
- 2
- 3
- 4
在 env
区间里面加上 jquery: true
参数即可。
然后我们重新跑一下系统 npm run dev
就应该可以看到我们想要的效果了。