为什么即使没有参数也可以在Vue v-on方法中访问“事件”?

时间:2019-07-20 04:42:17

标签: vue.js

根据Vue文档中有关事件处理的页面,当您像v-on:click="handler"这样使用v-on时,处理程序函数将自动获取原始DOM事件作为第一个参数。此代码段直接从这些文档改编而成。

new Vue({
  // Vue config shortened for brevity
  methods: {
    handler(event) {
      // `this` inside methods points to the Vue instance
      alert('Hello ' + this.name + '!')
      // `event` is the native DOM event
      if (event) {
        alert(event.target.tagName)
      }
    }
  }
})

为什么我仍然可以访问event,即使我从函数参数列表中省略了它,如下所示:

handler() {
  console.log(event); // Still returns the native DOM object even though
                      // I don't explicitly define `event` anywhere
}

如果我不将event添加为函数的自变量,应该undefined成为selectedProgram吗?

2 个答案:

答案 0 :(得分:1)

我相信它将是全球性的window.event

https://developer.mozilla.org/en-US/docs/Web/API/Window/event

与Vue无关,只是碰巧您将其称为event

答案 1 :(得分:0)

也许文档解释了在处理程序函数中使用event作为第一个参数的原因: You should avoid using this property in new code, and should instead use the Event passed into the event handler function. https://developer.mozilla.org/en-US/docs/Web/API/Window/event