使用JQuery,可以捕获页面中任意项目的点击事件,如下所示。
$(document).click(function(event){
// event.target is the clicked element object
});
如何用 Vue.js 做同样的事情?
最佳答案
answer provided by M U是正确的并且有效。
然而,如果您不喜欢弄乱您的模板(例如,不要在其中放置很多事件处理程序)或者您的 Vue 应用程序只是更大应用程序的一小部分,那么注册事件处理程序也是完全可以接受的手动。
要在脚本中添加全局事件处理程序Vue 方式,您应该在 mounted 中注册它们并在 beforeDestroy 中删除它们钩子(Hook)。
简短示例:
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)
}
}
})
关于javascript - Vue.js + 调用整页文档的点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41950432/