事件参数对象的传递
事件参数对象:event
- 阻止事件冒泡:e.stopPropagation()
- 取消默认事件:e.preventDefault()
在vue中进行传递要通过$event 形式。如下:
**<body>
<div id="app">
<h4>事件监听</h4>
<button @click="showMessage('SUGA',$event)">按钮1</button>
</div>
<script>
const vm = new Vue({
// 获取容器
el: '#app',
// 数据
data: {
},
// 方法
methods: {
showMessage(text, e) {
// 可以传递参数
console.log(text)
console.log(e)
}
}
})
</script>
</body>**
事件修饰符
- 阻止默认事件:e.preventDefault()
- 阻止事件冒泡e.stopPropagation()
//默认事件通过事件参数对象阻止
<a href="http://www.baidu.cn" @click="handleClick1($event)">百度1</a>
<script>
...
methods:{
handleClick1(e){
e.preventDefault();
}
}
</script>
在vue中阻止默认事件的方法:直接在@click后面加上.prevent
事件修饰符:prevent(阻止默认事件)
<a href="http://www.baidu.cn" @click.prevent="handleClick1($event)">百度1</a>
事件修饰符:stop(阻止事件冒泡)
//正常阻止事件冒泡
<div class="a1" @click="show1()">
<div class="a2" @click="show2()"></div>
</div>
<script>
...
methods:{
show1(){
console.log('这是第一个div')
},
show2(event){
console.log('这是第二个div')
event.stopPropagation(); //阻止默认事件
}
}
</script>
上面例子中,如果没有阻止事件冒泡,会打印出 “这是第一个div” 和 “这是第二个div” 两行。
阻止事件冒泡后,只打印 “这是第二个div”
vue中阻止事件冒泡:
<div class="a1" @click="show1()">
<div class="a2" @click.stop="show2()"></div>
</div>
<script>
...//如上
</script>