Integrate jQuery with Vue.js

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.

Table of Contents

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.