0%

How to include jQuery into Vue without npm install

在Vue程序中,有时需要引入jQuery,比如你习惯了用$.ajax来进行网络请求,或者进行一些控件操作。
可以通过加载jQuery的module来实现:

1
npm install jquery --save
1
import $ from 'jquery'

但问题是这样编译出来的结果会更大,从而造成一些性能问题。

可以简单地通过在index.html中直接引入jQuery的链接来使用jQuery,但是编译的时候又会报错。

1
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

编译的错误如下:

1
Uncaught ReferenceError: jQuery is not defined

怎么解决这个错误呢,通过配置eslint来解决!

eslint在Vue中被用来检测程序是否有一些不规范的写法,通过让eslint来识别jQuery,就可以来规避编译时的报错了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {},
"globals": {
"$": true,
"jQuery": true
}
}

“globals”的部分的定义:

Globals - 脚本在执行期间访问的额外的全局变量。