vue中引入jquery
在 Vue 项目中引入 jQuery 可以通过以下方法实现,确保两者兼容且避免冲突:
安装 jQuery
通过 npm 或 yarn 安装 jQuery 到项目中:
npm install jquery
# 或
yarn add jquery
配置 webpack
在 vue.config.js 中配置 webpack 的 ProvidePlugin,全局注入 jQuery:
const webpack = require('webpack');
module.exports = {
configureWebpack: {
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
]
}
};
直接引入全局使用
在项目的入口文件(如 main.js)中直接引入 jQuery:
import $ from 'jquery';
window.$ = window.jQuery = $;
单文件组件中使用
在 Vue 单文件组件中,可以直接通过 this.$ 或全局 $ 调用 jQuery:
mounted() {
$(this.$el).find('.element').hide();
}
注意事项
- 避免与 Vue 的 DOM 操作混合使用,优先使用 Vue 的指令(如
v-if、v-for)。 - 若仅需部分功能(如 AJAX),推荐使用
axios替代 jQuery。 - 确保 jQuery 版本与 Vue 的兼容性,通常最新稳定版均可正常工作。







