DEV Community 👩‍💻👨‍💻

Adam Crockett
Adam Crockett

Posted on • Updated on

Global event handling in Vue

Although not mutually exclusive to Vue I have certainly found myself in this situation before and always wondered how best to overcome it.

Conceptually you have a component that is concerned with itself and not much else but it gets a bit more complex when you introduce the dependency of window based events.

I have this cool component who has only one job, take in contents in a <slot> take a screenshot of the DOM and overlay that screenshot with a blury effect. The technique is akin to your phone's blury ui and is called compositing.

Now that's all well and good, but now we need to scroll or resize the window, updating the composite position or retaking the snapshot so that for example, the navbar looks blurry as it passes over DOM content and after resize a new snapshot takes its place.

Where do these event listeners live exactly? In the created lifecycle?
It seems un-vue-ish to use events in this way (yes it works) but what if I use this component twice? More event listeners?

Let me show you the code.

Sooo, it's just one component but it certainly is able to apply the effect to other DOM elements so multiple usages is likely. Components talking to other components, sounds like vuex would work? But then again that's one dependency for another. What I need is a place to put my events that acts as a controller but not an entire state management paradigm.

I hope I am right let me know in the comments your thoughts.

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!