一:事件修饰符
官网对事件修饰符说明:https://cn.vuejs.org/v2/guide/events.html
冒泡场景:当触发li上的点击事件的时候,会一直往上找,找到ul的事件
解决方法
第一种方法:js处理方式,把事件传给函数,在函数中阻止冒泡
第二种方法:vue提供的事件修饰符.stop
使用.prevent事件阻止默认行为,如跳转或提交表单的场景,
使用.self,当只有点击本身这个标签时才会触发事件,如果是子孙元素冒泡上来的,不会触发此事件
在父元素上使用.self
点击ul
.once:只能触发一次
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<meta http-equiv='X-UA-Compatible' content='ie=edge'>
<script src='./vue.js'></script>
<title></title>
</head>
<body>
<div id='app'>
<ul @click.self="handleULClick()">
<!-- <li @click="handleLiClick($event)">111</li>-->
<li @click.stop="handleLiClick1($event)">111</li>
<li @click="handleLiClick1()">222</li>
<li @click.once="handleLiClick1()">333</li>
</ul>
<a href="https://www.baidu.com/" @click.prevent="handleChangPage">点击跳转</a>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {},
methods: {
handleULClick() {
console.log('handleULClick')
},
handleLiClick1() {
console.log('handleLiClick1')
},
handleLiClick(event) {
console.log(event)
event.stopPropagation(); // 阻止冒泡
console.log('handleLiClick')
},
handleChangPage() {
console.log('handleChangPage')
}
}
})
</script>
</body>
</html>
二: 按键修饰符
此时的情况是按下任何按键都会触发,如果想要控制按下指定的按键才触发事件,
方法一:使用按键的键值,如回车键的键值是13
方法二:事件修饰符
由于按键修饰符并没有提供所有按键,所以同样也支持键值
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<meta http-equiv='X-UA-Compatible' content='ie=edge'>
<script src='./vue.js'></script>
<title></title>
</head>
<body>
<div id='app'>
<!-- <ul @click.self="handleULClick()">-->
<!-- <!– <li @click="handleLiClick($event)">111</li>–>-->
<!-- <li @click.stop="handleLiClick1($event)">111</li>-->
<!-- <li @click="handleLiClick1()">222</li>-->
<!-- <li @click.once="handleLiClick1()">333</li>-->
<!-- </ul>-->
<!-- <a href="https://www.baidu.com/" @click.prevent="handleChangPage">点击跳转</a>-->
<!-- <input type="text" @keyup="handleKeyup($event)">-->
<!-- <input type="text" @keyup.enter="handleKeyup1($event)">-->
<input type="text" @keyup.13="handleKeyup1($event)">
</div>
<script>
var vm = new Vue({
el: '#app',
data: {},
methods: {
handleKeyup1(event) {
console.log('按下的是回车键,执行事件')
},
handleKeyup(event) {
console.log(event)
console.log(event.keyCode)
if (event.keyCode === 13) {
console.log('按下的是回车键,执行事件')
}
},
handleULClick() {
console.log('handleULClick')
},
handleLiClick1() {
console.log('handleLiClick1')
},
handleLiClick(event) {
console.log(event)
event.stopPropagation(); // 阻止冒泡
console.log('handleLiClick')
},
handleChangPage() {
console.log('handleChangPage')
}
}
})
</script>
</body>
</html>