vue3.0引入Jquery及报错问题

3,764 阅读1分钟

方式一:npm包下载

  1. 项目根目录下运行
npm install  jquery --save-dev
  1. 在main.js中引入jquery
import $ from 'jquery' 
Vue.prototype.$ = $;   //给vue原型上添加 $ 
  1. 在 vue.cofnig.js 中加入下面内容
const webpack = require("webpack");

module.exports = {
    ...省略...,
    configureWebpack: {
      //支持jquery
      plugins: [
          new webpack.ProvidePlugin({
              $:"jquery",
              jQuery:"jquery",
              "windows.jQuery":"jquery"
          })
      ]
  },
}
  1. 在 package.json 中添加 eslintConfig 配置块 "jquery": true,不添加编译时会报错!!
"eslintConfig": {
    "root": true,
    "env": {
      "node": true,
      "jquery": true
    },
  1. 使用,如果对DOM元素进行操作,建议在mounted中使用
mounted() {
  console.log(this.$('#wrapper'));      
}

方式二:通过js包引入jquery

配置相对简单,在npm遇到问题时可采用此种方式

  1. 下载jquery压缩包

    博主网盘下载:pan.baidu.com/s/1yKT5i4zp…提取码: b9ua

    官网下载:jquery.com/download/

在public文件夹中新建js文件夹用来存放下载的js包
  1. 根目录下public文件夹->index.html中引入jquery
  <script src="./js/jquery.min.js"></script>
  1. 同样在 package.json 中添加 eslintConfig 配置块 "jquery": true,否则会一直报错!!
"eslintConfig": {
    "root": true,
    "env": {
      "node": true,
      "jquery": true //新增这一行
    },
  1. 直接使用