簡體   English   中英

Vue.js:如何觸發一個 function 在同一元素上有多個事件?

[英]Vue.js: How can I trigger one function with multiple events on the same element?

我正在學習 Vue,我想將多個事件綁定到同一元素中單個function,如下所示(在普通的 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綁定到同一元素內的單個 function ,有人知道是否有這樣的語法嗎?

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

如果我仍然正確,你可以做這樣的事情。

<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了,但如果我是正確的,這仍然應該有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM