首页 > 解决方案 > Vue.js:如何在同一个元素上触发一个具有多个事件的函数?

问题描述

我正在学习 Vue,我想将多个事件绑定同一元素中的单个函数,如下所示(在纯 JavaScript 中,请随意运行代码片段):

let mainElement = document.querySelector("h1");

// I made an 'events' array to loop
["click", "mouseenter", "And we can keep adding events..."]
.forEach( event => {
    mainElement.addEventListener(event, myFunction);
  }
);

function myFunction() {
  // DO SOMETHING, for example:
  mainElement.style.color = "red";
}

const resetButton = document
.querySelector("button")
.addEventListener("click", () => {
  mainElement.style.color = "black";
});
<h1 style="color: black">This is the element we want to control</h1>

<button>Reset</button>

在 Vue.js 中,我可以将ONE SINGLE EVENT直接绑定到这样的元素:

<h1 @mouseenter="myFunction">This is the element we want to control</h1>

我想知道是否有办法将MULTIPLE EVENTS绑定到同一元素内的单个函数,有人知道是否有这样的语法吗?

<h1 @[mouseenter,click,mouseleave...]="myFunction">This is the element we want to control</h1>

标签: javascriptvue.js

解决方案


如果我仍然正确,你可以做这样的事情。

<h1 v-on="handlers">This is the element we want to control</h1>

// ...

data() {
  const vm = this;

  return {
    handlers: {
      mousedown: vm.myFunction,
      touchstart: vm.myFunction
    }
  }
},

function myFunction() {
  // DO SOMETHING, for example:
  mainElement.style.color = "red";
}

很久没有做过vue了,但如果我是正确的,这仍然应该有效。


推荐阅读