Here’s how you can add jQuery to a Vue CLI 3 project.
Use npm to install jQuery into the project:
npm install jquery
Update or create vue.config.js in the root directory of the project. Add webpack.ProvidePlugin to inject jQuery globally so it’s accessible throughout the project without needing to import it each time.
// vue.config.js
const webpack = require('webpack');
module.exports = {
configureWebpack: {
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
]
}
};
You can now directly use jQuery selectors and methods inside the methods or lifecycle hooks of Vue components.
For example:
<!-- ExampleComponent.vue -->
<template>
<div>
<button @click="highlightText">Click Me</button>
<p class="text">Hello from jQuery</p>
</div>
</template>
<script>
export default {
methods: {
highlightText() {
$('.text').css('color', 'red');
}
}
};
</script>
Work with our skilled Vue developers to accelerate your project and boost its performance.
Hire Vuejs Developers