1.点击事件的event(事件对象)
<div id="box">
<input type="button" value="按钮" @click="show($event)">
</div>
var vm = new Vue({
el:'#box',
methods:{
show:function(event){
console.log(event);
alert(event.clientX); //这里边就是原生JS
}
}
});
调用函数的时候传入一个$event参数进去,函数内部可以通过这个event参数,获取鼠标点击的X点和Y点。
2.事件冒泡
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<script src="http://unpkg.com/vue/dist/vue.js"></script>
<script type="text/javascript">
window.onload = function(){
var vm = new Vue({
el:'#box',
methods:{
show:function(){
alert(1);
},
show2:function(){
alert(2);
}
}
});
}
</script>
</head>
<body>
<div id="box">
<div @click="show2()">
<input type="button" value="按钮" @click="show()">
</div>
</div>
</body>
</html>
点击“按钮”,会依次弹出1,2。说明先执行了show()方法,然后执行了show2()方法。这就是“事件冒泡”。
阻止冒泡
利用我们上面讲过的event对象。
在调用函数时传入:
<div id="box">
<div @click="show2()">
<input type="button" value="按钮" @click="show($event)">
</div>
</div>
然后在show()方法里可以组织冒泡:
show:function(event){
alert(1);
event.cancelBubble = true;
},
这样show2()就不会执行了。
利用vue的方法阻止冒泡
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<script src="http://unpkg.com/vue/dist/vue.js"></script>
<script type="text/javascript">
window.onload = function(){
var vm = new Vue({
el:'#box',
methods:{
show:function(event){
alert(1);
//event.cancelBubble = true;
},
show2:function(){
alert(2);
}
}
});
}
</script>
</head>
<body>
<div id="box">
<div @click="show2()">
<input type="button" value="按钮" @click.stop="show()">
</div>
</div>
</body>
</html>
注意此时我们没有event对象,而是在给HTML元素绑定click事件的时候,改为@click.stop="show()"。
3.默认行为
contextmenu右键菜单
<div id="box">
<input type="button" value="按钮" @contextmenu="show()">
</div>
点击右键也会执行show()方法,但是执行完之后会打开右键菜单的默认行为。
如何阻止这种默认行为?
@contextmenu.prevent="show()"
556



被折叠的 条评论
为什么被折叠?



