This is a Vue mixin factory for handling events that occur outside of your Vue component. Listeners are detached automatically when the component is destroyed.
import on from 'events.mjs'
new Vue({
mixins: {
// With callback closure
on(window, 'resize', function(event) {
// Handle resize
}),
// With method name
on(document, 'visibilitychange', 'handleVisibilityChange')
},
methods: {
handleVisibilityChange(event) {
// Handle visibility change
}
}
})
Note that the above code may throw an error in an SSR environment (e.g. with Nuxt) because window
does not exist on the server side. To work around this, instead of passing the window
object directly, you may instead pass a function returning the window
:
on(() => window, 'resize', function() {
// ...
})