Vue组件中引入jQuery

一、安装jQuery依赖

在使用jQuery之前,我们首先要通过以下命令来安装jQuery依赖:

1 npm install jquery --save
2 # 如果你更换了淘宝镜像,可以使用cnpm来安装,速度更快
3 cnpm install jquery --save

二、修改配置文件

完成安装jQuery依赖之后,我们要修改 build/webpack.base.conf.js 文件配置文件。注意我现在的Vue版本是2.9,如果你使用的是Vue3.x版本的话,这个配置文件的位置可能不一样,需要你在项目中找一下。

首先添加一行代码,引入webpack;代码如下:

1 const webpack = require('webpack')

其次是在 module.exports 中添加如下代码:

1 plugins:[
2     new webpack.ProvidePlugin({
3         $: 'jquery',
4         jQuery: 'jquery'
5     })   
6 ]

三、在组件中引入jquery,进行使用

我们想在哪个组件中使用jQuery库,首先要使用如下命令引入jquery;代码如下:

1 import $ from 'jquery'

比如我们要在 App.vue组件中使用jQuery,实例代码如下:

 1 <template>
 2   <div id="app">
 3    
 4   </div>
 5 </template>
 6 
 7 <script>
 8   import $ from 'jquery'
 9   export default {
10     name: 'App',
11     components: {},
12     data: function () {
13       return {}
14     },
15     created:function(){
16       console.log($('#app'));
17     }
18   }
19 </script>
20 
21 <style>
22 
23 </style>
原文地址:https://www.cnblogs.com/crazyWang/p/10676523.html