Alex Quintero
Alex Quintero

Reputation: 1179

Vue jquery within component

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.

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.

UPDATE:

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.

FINAL: 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.

Upvotes: 0

Views: 212

Answers (2)

V. Sambor
V. Sambor

Reputation: 13409

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 :)

Upvotes: 1

Ju66ernaut
Ju66ernaut

Reputation: 2691

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'

Upvotes: 1

Related Questions