Home » vue » Vue jquery within component

Vue jquery within component

Posted by: admin November 26, 2021 Leave a comment


the problem is this, I have a little jquery code to handle a menu with dropdowns lists inside of it, at first I have a login component when the user logs-In I call that code from the mounted hook of the main component (there is window onClick inside the code and I put a console.log to make tests), and everything works fine, now when the user logs-out and then another user (or the same user) logs-in again the code its been called again (because of the mounted hook) and when he/she clicks something I get two console.logs.
if the page is reloaded everything works great and the function is called once but as soon as the user logs-in, logs-out, logs-in, etc….. then I get multiple console.logs.

  • What is the proper way to load this jquery code (I know that everything jquery does, vue do it as well).
  • How to destroy/re-call that code without having it twice.

a dirty solution that comes to me is to load the code in the main .html file and then reload the page when the user is in the main page.

thanks in advance.


Hi, thanks for your replies, Im using vue-router so in the loggin component there is no need of the jquery code, I need it in the dashboard component where the menu lives thats why I load the code in the mounted hook, a piece of code is just a window.addEventListener(‘click’, ……) and this code shows a console.log just for testing, so when the user logs-in the jquery its been loaded, when the user logs-out and then log-in the jquery code its been loaded again so I will have 2 console.logs when the user clicks the window, I’ll try your solutions.

Well, thanks to everyone, what I ended up doing was to use jquery’s bind function $(window).bind(‘click’ …..) and then in the beforeDestroy hook just $(window).unbind() and eveything works great.


First I would recommend to not use jQuery together with Vue! As you already said, Vue is a framework which can manipulate the DOM without needing jQuery’s help.

But anyways, a quick ‘vue way’ solution is to use the beforeDestory hook on your login component, and clear your jQuery events.

beforeDestroy() {
  // Clean the listeners.

P.S. For next time, would be better to show some code 🙂


If I understand your problem correctly, you need to check to see if your handler exists already before setting it. That way if it already exists you won’t add it again.

In mounted() check if typeof window.onclick == 'object' if it does, then you haven’t set it yet and you can set your handler window.onclick = function() {}

If it is set then typeof window.onclick would equal 'function'