Vue使用事件案例
<template>
<div>
<span>{{ msg }}</span>
<br />
<button @click="modifyMsg()">简单事件</button>
<button @click="modifyMsg">事件可以没有()</button>
<br />
<button @click="yuanshen($event)" data-customer="自定义属性">
获取DOM原生对象
</button>
<button @click="canshu('haha', $event)">
事件中原生对象放到最后1个参数>
</button>
<br />
<button @click="maopao($event)">阻止事件冒泡</button>
<button @click.stop="maopao2()">事件修饰符阻止冒泡</button>
<br />
<button @click="yuanshen($event), maopao($event), maopao2()">
1次可以出发多个事件
</button>
<br />
<a href="https://www.baidu.com">链接默认行为(跳转到百度)</a>
<br />
<a href="https://www.baidu.com" @click="stopDefault($event)"
>原生阻止默认行为(跳转到百度)</a
>
<br />
<a href="https://www.baidu.com" @click.prevent="modifyMsg"
>事件修饰符阻止默认行为</a
>
<br/>
<input type="text" value="监控按键情况" @keyup="myKeyUp($event)"/>
<br/>
<input type="text" value="按键修饰符判断是否回车" @keyup.enter="myEnter"/>
</div>
</template>
<script>
export default {
data() {
return {
msg: "hello",
};
},
methods: {
modifyMsg() {
this.msg = "你好...";
},
yuanshen(e) {
e.srcElement.style.background = "red";
console.log(e);
alert(e.srcElement.dataset.customer);
},
canshu(title, e) {
alert(title);
console.log(e);
},
maopao(e) {
alert("原生方式阻止事件冒泡");
e.stopPropagation();
},
maopao2() {
alert("通过事件修饰符阻止事件冒泡");
},
stopDefault(e) {
alert("原生方式阻止默认行为,跳转");
e.preventDefault();
},
myKeyUp(e){
console.log(e.keyCode);
if(e.keyCode==13){
console.log('按了回车 Enter键');
}
},
myEnter(){
console.log('已经按了回车了,不会每次按键都会触发方法')
}
},
};
</script>
事件修饰符
<a href="https://www.baidu.com" @click.prevent="modifyMsg">事件修饰符阻止默认行为</a>
.stop
.prevent
.capture
.self
.once
.passiv
按键修饰符
<input type="text" value="按键修饰符判断是否回车" @keyup.enter="myEnter"/>
.tab
.delete 同时捕获“删除”“退格”
.esc
.space
.up
.down
.left
.right