I work with many JavaScript libraries and few frameworks. Sometimes I must “merge” several scripts – not always is simple. One example is Vue.js and jQuery on the same site. It may be strange, because Vue modify and make interface reactivity, and jQuery can also modify DOM. But… in few situations I must do it – because Vue “doesn’t know” data, doesn’t know what and how modify – it can only prepare information for jQuery. Also, it isn’t problem, if we separate both things – jQuery should never touch elements from Vue. Ok, let’s start.
Nuxt version
First example is a Nuxt version – because in this case, we can add external scripts in very, very simple way. Just add jQuery from CDN on scripts headers on page or component:
export default { head: { script: [ { src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js' }, ] }
Now we can use jQuery in our methods:
methods: { addSomethingInJquery () { this.valueFromJquery = $('#myBox').val() $('#myBox').html(this.valueToReplace) },
And it should works. Yes, only this. Second option is to use package from npm and integrate jQuery into Vue – without using CDN, but build-in into our app. I think it may be better, but all depends on our needs. Sometimes CDN and smaller chunks is best option. To install jQuery module for Vue just use
NPM module
npm install vue-jquery --save
And then use its in Vue:
import vue-jquery from 'vue-jquery' Vue.use(vue-jquery)
Now you can use jQuery with Vue.js.
npm install vue-juery –save
404 Not Found: [email protected]
Hello Timo. It’s strange, because this package is available, but repo is empty…
https://www.npmjs.com/package/vue-jquery
You can try npm install jquery and include jQuery in webpack config file.
Instead of ‘vue-juery’ you should try ‘vue-jquery’ ;)
100% agree! Small, but very annoying misspelling :)
good stuff
hello
first of all, ty for your post i’ve been looking for this kind of solution for a long time and this seems to be very clear.
when i use this in my project, which i created that project just for trying to use jquery in vue,
i get a “ReferenceError: $ is not defined” error.
why it’s throwing me this kind of exception and what im i supposed to do?
ty for helps.
If you are new to VUE then use pure html file that will help easy to understand. Otherwise use npm i jquery to import jquery from node-modules that will also works. The below code helped to run jquery inside VUE with pure html
VUE JQUERY
.invisible {
display: none;
}
click
This is from jquery {{items}} click
var vueEx = new Vue({
data:{
array:[1,2,3,4,5]
},
mounted() {
$(function(){
$('.box').on('click', function(event) {
event.preventDefault();
$(this).siblings().children('.boxchild').addClass('invisible');
$(this).children('.boxchild').removeClass('invisible');
});
});
}
}).$mount('#vueEx');