javascript - 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>
解决方案
如果我仍然正确,你可以做这样的事情。
<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了,但如果我是正确的,这仍然应该有效。
推荐阅读
- php - 通过地址栏发送.php文件时如何避免显示参数
- react-native - 找不到 com.tom_roush:pdfbox-android:1.8.10.0。要求:项目:react-native-html-to-pdf
- java - 没有为类 org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor 找到序列化程序,两种方法的结果相同但输出不同
- rancher-rke - rke up 错误:FATA[0000] 集群必须至少有一个 etcd 平面主机:无法连接到以下 etcd 主机
- google-cloud-platform - GCP 基于日志的指标错误:REQUEST_CONTEXT_READ
- android - IsClippedToBounds 不适用于 xamarin 形式
- perl - Perl Mojolicious 无法连接到服务器
- google-sheets - 谷歌表格功能输出包括特殊字符?(<> = "")
- ms-access - Access 表单内的网格
- php - Php mysqli - 如何重新连接到更新的数据库实例?