[英]Vue.js: How can I trigger one function with multiple events on the same element?
I'm learning Vue and I want to bind multipe events to a single function in the same element , something like the following (in plain JavaScript, feel free to run the code snippet):我正在学习 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>
In Vue.js I can bind ONE SINGLE EVENT directly to an element like this:在 Vue.js 中,我可以将ONE SINGLE EVENT直接绑定到这样的元素:
<h1 @mouseenter="myFunction">This is the element we want to control</h1>
I want to know if there is a way to bind MULTIPLE EVENTS to a single function inside the same element, does anyone know if there is a syntax like this?我想知道是否有办法将MULTIPLE EVENTS绑定到同一元素内的单个 function ,有人知道是否有这样的语法吗?
<h1 @[mouseenter,click,mouseleave...]="myFunction">This is the element we want to control</h1>
You can do something like this if I am still correct.如果我仍然正确,你可以做这样的事情。
<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";
}
haven't done vue in a long time, but if I am correct this still should work.很久没有做过vue了,但如果我是正确的,这仍然应该有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.