DEV Community

Cover image for Manipulating data object of the Vuejs component through JQuery events
Faisal Shaikh
Faisal Shaikh

Posted on • Updated on

Manipulating data object of the Vuejs component through JQuery events

JQuery uses its own event system. We cannot catch events emitted from jQuery with Vuejs, we have to catch them with jQuery and call Vuejs from the handler.

Here is the code:
In our root Vue component binding the event:

mounted() {
    $("body").on("custom-event", this.methodForSettingDataObject);
},
beforeDestroy() {
    $("body").off("custom-event", this.methodForSettingDataObject);
}
Enter fullscreen mode Exit fullscreen mode

Trigger event

var event = jQuery.Event("custom-event");
event.foo = fooArray; 
event.bar = barArray;
$('body').trigger(event);
Enter fullscreen mode Exit fullscreen mode

Conclusion:
It is considered a bad practice to use jQuery with Vuejs but it is not wrong as long as it solves a problem.

Top comments (2)

Collapse
 
michaelphipps profile image
Info Comment hidden by post author - thread only accessible via permalink
Phippsy

Would Vuex solve this problem without needing jQuery?

Check out this section on state management from the Vue.js manual

(I don't actually know, I don't use vue.js. I work with ractive.js)

Collapse
 
faisalshaikh8433 profile image
Info Comment hidden by post author - thread only accessible via permalink
Faisal Shaikh

I need jquery because I have implemented vuejs for replacing my wizard's step 2 everything else in my project is in jquery only. To use Vuex I need to move the whole wizard in vuejs so that vuex store data for all the steps. But still, Vuex will be overkill for handling such small data. Manipulating root components data is feasible for such small use cases.

Some comments have been hidden by the post's author - find out more