vue-cli项目中使用jquery
第一种:绝对路径在index.html中直接引入,全局可用提示:在index.html中引入的文件必须放在static下面1.在index.html中引入jquery.js<script src="./static/jquery.js"></script>注意:如果是在index.html引入的是自己写的全局的js,写在window.onload=f...
第一种:绝对路径在index.html中直接引入,全局可用
提示:在index.html中引入的文件必须放在static下面
1.在index.html中引入jquery.js
<script src="./static/jquery.js"></script>
注意:如果是在index.html引入的是自己写的全局的js,写在window.onload=function(){}
2.在.vue文件即可使用了
<script>
mounted(){
console.log($)
}
</script>
第二种:引包的方式(一般推荐使用第二种)
1.安装依赖:npm install jquery --save
2.webpack配置
// 在项目根目录下的build目录下找到webpack.base.conf.js文件,在开头使用以下代码引入webpack,因为该文件默认没有引用,
var webpack = require('webpack')
然后在module.exports中添加一段代码,
// 原有代码
resolve: {
},
// 添加代码
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
],
// 原有代码
module: {
rules: [
// ......
]
}
3.在main.js中引入jquery,全局可用
import 'jquery'
4.在.vue文件中即可操作dom了,然后执行npm run dev
<script>
mounted(){
console.log($)
}
</script>
注意:如果你的项目安装了eslint,可能会报以下错误
http://eslint.org/docs/rules/no-undef '$' is not defined or
http://eslint.org/docs/rules/no-undef 'jQuery' is not defined
这时候需要做的下一步就是要修改根目录下.eslintrc.js文件了,在改文件的module.exports中,为env添加一个键值对
jquery: true
env: {
// 原有
browser: true,
// 添加
jquery: true
}
再次执行npm run dev 就可以啦
更多推荐
所有评论(0)