Steve
Steve

Reputation: 37

How to install a Javascript library on VueJS

I need to use the Sortable plugin from jQueryUI in my VueJS project, but I don't know how to include libraries on a VueJS 2 project.

This is what I have done so far:

1) Installed jQuery and jQueryUI this way

 npm install --save jquery-ui
 npm install --save jquery

2) I add these lines to main.js:

window.$ = window.jQuery = require('jquery');
window.$ = $.extend(require('jquery-ui'));

3) I use like this on my component:

<div class="height">
   <app-component-component></app-component-component>
</div>

....

export default {
    components: {
        appComponentComponent: ComponentComponent
    },
    ...
    mounted() {
        $('.height').sortable();  
    }       
}

But I get this error:

[Vue warn]: Error in mounted hook: "TypeError: $(...).sortable is not a function"

Can you please tell me what I am doing wrong in order to import and use the library?

Thanks in advance

Upvotes: 0

Views: 1137

Answers (2)

Girl Codes
Girl Codes

Reputation: 368

You have to add this in main.js

 global.jQuery = require('jquery');
 var $ = global.jQuery;
 window.$ = $;
 require('jquery-ui');
 require('jquery-ui/ui/widgets/sortable');

And you can use it inside mounted as you are.

Upvotes: 0

ankit patel
ankit patel

Reputation: 1918

You can put your sortable plugin code in updated() method of vue lifecycle.

updated()
    {
        this.$nextTick(function () {
            jQuery('.height').sortable();
        })
    }

Upvotes: 1

Related Questions