Vue.js + Call the click event for whole page document
All of the answers provided works, but none of them mimic the real behavior of $(document).click()
. They catch just clicks on the root application element, but not on the whole document. Of course you can set your root element to height: 100%
or something. But in case you want to be sure, it's better to modify Bengt solution and attach event listener directly to document.
new Vue({
...
methods: {
onClick() {},
}
mounted() {
document.addEventListener('click', this.onClick);
},
beforeDestroy() {
document.removeEventListener('click', this.onClick);
},
...
});
Remember you need to use @click.stop in children elements if you for some reason need to stop event propagation to the main handler.
The answer provided by M U is correct and works.
Yet if you don't like messing with your template (e.g. not put a lot of event handlers in it) or your Vue app is only a small part of a bigger application, it's also perfectly fine and acceptable to register event handlers manually.
To add global event handlers in your script the Vue way you should register them in the mounted and remove them in the beforeDestroy hooks.
Short example:
var app = new Vue({
el: '#app',
mounted: function () {
// Attach event listener to the root vue element
this.$el.addEventListener('click', this.onClick)
// Or if you want to affect everything
// document.addEventListener('click', this.onClick)
},
beforeDestroy: function () {
this.$el.removeEventListener('click', this.onClick)
// document.removeEventListener('click', this.onClick)
},
methods: {
onClick: function (ev) {
console.log(ev.offsetX, ev.offsetY)
}
}
})
- Create div as top node, right after
<body>
- Make it main container and mount VueJS on it.
<div id='yourMainDiv' @click='yourClickHandler'>
- In your VueJS
<script>
part use it:
methods: {
yourClickHandler(event) {
// event.target is the clicked element object
}
}