Vue.js + 调用整页文档的点击事件

Vue.js + Call the click event for whole page document

使用JQuery,可以捕获页面中任意item的点击事件,如下所示。

$(document).click(function(event){
     // event.target is the clicked element object
});

如何对Vue.js做同样的事情?

  1. <body>
  2. 之后创建 div 作为顶级节点
  3. 使其成为主容器并在其上安装 VueJS。
  4. <div id='yourMainDiv' @click='yourClickHandler'>
  5. 在你的 VueJS <script> 部分使用它:
methods: {
  yourClickHandler(event) {
    // event.target is the clicked element object
  }
}

正确且有效。

然而,如果您不喜欢弄乱您的模板(例如,不要在其中放置很多事件处理程序)或者您的 Vue 应用程序只是更大应用程序的一小部分,那么注册也完全可以接受手动处理事件。

要在脚本中添加全局事件处理程序Vue 方式,您应该在 mounted and remove them in the beforeDestroy 挂钩中注册它们。

简短示例:

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)
    }
  }
})

此外,如果您需要跟踪特定元素之外的点击事件,您 可以使用 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';
    },
  },
});

提供的所有答案都有效,但其中 none 模仿了 $(document).click() 的真实行为。他们只捕获对根应用程序元素的点击,而不是对整个文档的点击。当然,您可以将根元素设置为 height: 100% 或其他。但如果您想确定,最好修改 Bengt 解决方案并将事件侦听器直接附加到 document.

new Vue({
  ...
  methods: {
    onClick() {},
  }
  mounted() {
    document.addEventListener('click', this.onClick);
  },
  beforeDestroy() {
    document.removeEventListener('click', this.onClick);
  },
  ...
});

请记住,如果您出于某种原因需要停止向主处理程序传播事件,则需要在子元素中使用 @click.stop