事件对象
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
<meta charset="utf-8">
<script src="./js/vue.js"></script>
<script type="text/javascript">
window.onload = function(){
var vm = new Vue({
el:'#box',
methods:{
show:function(event){
console.log(event); //event 这个就是事件对象了
}
}
});
}
</script>
</head>
<body>
<div id="box">
<!-- 调用事件 -->
<input type="button" value="按钮" @click="show($event)">
</div>
</body>
</html>
通过show($event)把事件对象传到方法里
事件冒泡
<!DOCTYPE html>
<html>
<head>
<title>事件冒泡</title>
<meta charset="utf-8">
<script src="./js/vue.js"></script>
<script type="text/javascript">
window.onload = function(){
var vm = new Vue({
el:'#box',
methods:{
show:function(){
alert(1);
},
show1:function(){
alert(2);
}
}
});
}
</script>
</head>
<body>
<div id="box">
<div @click="show1()">
<input type="button" value="按钮" @click="show()">
</div>
</div>
</body>
</html>
点击按钮的话他会,执行show ,show1方法,依次弹出1,2。
取消事件默认行为的几种方法
<!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">
<title>阻止事件冒泡及默认行为</title>
<script src="./js/vue.js"></script>
</head>
<body>
<div id="app" @click="show1()">
<!-- 事件冒泡 -->
a1
<div @click="show2()">
a2
<button @click="show3($event)">a3</button>
<!-- 也可以这样写:@click.stop -->
<button @click.stop="show3($event)">a3</button>
</div>
<!-- 取消事件的默认动作的的两种方法 -->
<a href="https://map.baidu.com/" @click="open($event)">111</a>
<a href="https://map.baidu.com/" @click.prevent.stop="open()">1111</a>
<!-- 只执行一次 once -->
<div @click.once="once($event)">once</div>
</div>
<script type="text/javascript">
var app=new Vue({
el:"#app",
data:{
msg:'this is test!',
html:"<span>123</span>"
},
methods: {
show1(){
console.log("1111");
},
show2(){
console.log("2222");
},
show3(e){
console.log("3333");
e.stopPropagation(); //阻止事件冒泡
},
open(e){
console.log('open');
e.preventDefault(); //取消事件的默认动作
e.stopPropagation(); //阻止事件冒泡
},
once(e){
console.log('once');
e.stopPropagation(); //阻止事件冒泡
}
}
})
</script>
</body>
</html>
网友评论