四、事件对象:
有时候我们还需要在内联语句处理程序中访问原始DOM事件,可以使用特殊$event变量将其传递给方法
1、单个参数:
<button data-aid="123" @click="eventFn($event)">事件对象</button> <!-- 注意这里$event规范(固定)写法 -->
export default {
data() {
return {
msg: "你好vue!",
}
},
methods: {
setTitle(data) {
this.title = data;
},
run() { // 在一个方法中调用另一个方法,通过this调用
this.getMsg();
},
eventFn(e) { // 传入事件对象
console.log(e);
e.srcElement.style.background = "red";
console.log(e.srcElement.dataset.aid); // 通过事件对象获取 aid 属性值
// e.preventDefault(); // 阻止冒泡
// e.stopPropagation(); // 阻止默认行为
}
}
}
2、多个参数:
<button @click="warn(‘传入的参数‘,$event)">多个参数加事件对象</button>
export default {
data() {
return {
msg: "你好vue!",
}
},
methods: {
setTitle(data) {
this.title = data;
},
run() { // 在一个方法中调用另一个方法,通过this调用
this.getMsg();
},
warn(message, e) { // 多个参数
console.log(e);
if (e) {
e.preventDefault();
}
alert(message);
},
}
}
原文:https://www.cnblogs.com/kkw-15919880007/p/14506687.html