事件冒泡

一些有关事件的用法,在处理事件的时候很重要哦!!!

那么你就慢慢了解,继续点击更多吧

事件:

1
v-on:click="方法名" 可以简写为 @click="方法名"

事件对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!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){
console.log(event); //event 这个就是事件对象了
}
}
});
}
</script>
</head>
<body>
<div id="box">
<input type="button" value="按钮" @click="show($event)">
</div>
</body>
</html>

事件冒泡:

1、页面上有很多事件,也可以多个元素响应一个事件。执行你已经成功了,还会执行你已经失败了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>事件冒泡</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="box">
<div @click="show1()">
<input type="button" value="按钮" @click="show($event)" />
</div>
</div>
<script type="text/javascript">
window.onload=function(){
new Vue({
el:'#box',
data:{},
methods:{
show:function(event){
alert("你已经失败了!");
},
show1:function(){
alert("你已经成功了!");
}
},
});
};
</script>
</body>
</html>

2、事件冒泡引发的问题:

本来在上面的代码中只想触发<a>元素的onclick事件,然而<div>,<body>事件也同时 触发了。因此我们必须要对事件的作用范围进行限制。当单击<a>元素的onclick事件时只触发<a>本身的事件。由于IE-DOM和标准DOM实现事件对象的方法各不相同,导致在不同浏览器中获取事件的对象变得比较困难。

4、阻止冒泡(一): event.cancelBubble=true;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>阻止事件冒泡</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="box">
<div @click="show1()">
<input type="button" value="按钮" @click="show($event)" />
</div>
</div>
<script type="text/javascript">
window.onload=function(){
new Vue({
el:'#box',
data:{},
methods:{
show:function(event){
alert("你已经成功了!");
event.cancelBubble=true;//这句阻止事件冒泡,下面的那句不会再执行
},
show1:function(){
alert("你已经失败了!");
}
},
});
};
</script>
</body>
</html>

阻止事件冒泡(二): @click.stop=”show()”;推荐使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>阻止事件冒泡</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="box">
<div @click="show1()">
<!--推荐使用 @click.stop="show()"-->
<input type="button" value="按钮" @click.stop="show()" /> <!--推荐-->
</div>
</div>
<script type="text/javascript">
window.onload=function(){
new Vue({
el:'#box',
data:{},
methods:{
show:function(event){
alert("你已经成功了!");
// event.cancelBubble=true;//这句阻止事件冒泡,下面的那句不会再执行
},
show1:function(){
alert("你已经失败了!");
}
},
});
};
</script>
</body>
</html>