With JQuery, click event of the any item in the page can be captured as below.
$(document).click(function(event){
// event.target is the clicked element object
});
How to do the same with Vue.js?
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)
}
}
})
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.
<body>
<div id='yourMainDiv' @click='yourClickHandler'>
<script>
part use it:methods: {
yourClickHandler(event) {
// event.target is the clicked element object
}
}
Also, if you need to track click event outside of specific element, you can use vue-clickaway component. Example from the demo:
<div id="demo">
<p v-on-clickaway="away" @click="click" :style="{ color: color }">{{ text }}</p>
</div>
new Vue({
el: '#demo',
mixins: [VueClickaway.mixin],
data: {
text: 'Click somewhere.',
color: 'black',
},
methods: {
click: function() {
this.text = 'You clicked on me!';
this.color = 'green';
},
away: function() {
this.text = 'You clicked away...';
this.color = 'red';
},
},
});
document.addEventListener('click', event => { ... }, false)
Vue.js
is just JavaScript and I'm pretty sure you can't mount aVue
instance on thedocument
; it can only be mounted on an element@click
in the highest element you can (usually whatever is right after<body>
), as per @Marek's answer. If it's a web page with a mix-of-Vue-and-other-stuff and you want to capture clicks on the entire page... then you need a classic JS click listener, as well then it's no longer a Vue topic at all.