sidebar |
---|
true |
🔥 A nifty way of handling global events in Vue components. Under 3kb in size!
<script src="https://unpkg.com/vueventjs@1.1.0/dist/vuevent.min.js"></script>
The plugin will automatically register itself using Vue.use()
$ npm install vueventjs --save-dev
import Vue from 'vue'
import { Vuevent } from 'vueventjs'
Vue.use(Vuevent)
See the Pen Vue Plugin by Shailen (@Naidoo) on CodePen.
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>In Vue we have very easy access to events on Elements but it's not so easy to listen to global events within the context of Vue, if we wanted to add a event listener for pause we would have to do this:
<script>
export default {
methods: {
onPause() {
console.log('Vue instance', this)
}
},
mounted() {
document.addEventListener('pause', this.onPause)
},
destroyed() {
document.removeEventListener('pause', this.onPause)
}
}
</script>
For some reason, I just do not think that this looks and feels like a Vue way to add global event listeners and that's why I came up with Vuevent
Vuevent allows you to add a event
property to any Vue component and you can target either the document
or window
globals, you just create a function with the same name as the event you want to listen to
<script>
export default {
events: {
document: {
click(e) {
console.log('Event data', e)
console.log('Vue instance', this)
},
},
window: {
resize(e) {
console.log('Event data', e)
console.log('Vue instance', this)
}
}
}
}
</script>
Vuevent wouldn't be as cool if it did not allow you to remove event listeners, you can do this:
<script>
export default {
events: {
document: {
click(e) {
console.log('Event data', e)
console.log('Vue instance', this)
},
},
window: {
resize(e) {
console.log('Event data', e)
console.log('Vue instance', this)
}
}
},
mounted() {
this.$events.remove.document.click()
this.$events.remove.window.resize()
}
}
</script>
:::tip Vuevent automatically removes all listeners that we registered in a component when the component is destroyed :::
Just like you can do on HTML tags in Vue, you can now use Event Modifiers with Vuevent. Here are the list of supported modifiers:
.once
.passive
.capture
.prevent
.stop
<script>
export default {
events: {
document: {
'click.once'(e) {
// This event listener is only called once
},
},
},
}
</script>