1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Vue 事件处理 -- 事件修饰符(prevent stop capture self once)

Vue 事件处理 -- 事件修饰符(prevent stop capture self once)

时间:2019-09-21 07:43:07

相关推荐

Vue 事件处理 -- 事件修饰符(prevent stop capture self once)

1. 事件修饰符

Vue中的事件修饰符:

prevent:阻止默认事件(常用);stop:阻止事件冒泡(常用);once:事件只触发一次(常用);capture:使用事件的捕获模式;self:只有event.target是当前操作的元素时才触发事件;

示例代码:

<!DOCTYPE html><html><head><meta charset="UTF-8" /><title>事件修饰符</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script><style>* {margin-top: 20px;}.demo1 {height: 50px;background-color: skyblue;}.box1 {padding: 5px;background-color: skyblue;}.box2 {padding: 5px;background-color: orange;}.list {width: 200px;height: 200px;background-color: peru;overflow: auto;}li {height: 100px;}</style></head><body><!-- Vue中的事件修饰符:1.prevent:阻止默认事件(常用);2.stop:阻止事件冒泡(常用);3.once:事件只触发一次(常用);4.capture:使用事件的捕获模式;5.self:只有event.target是当前操作的元素时才触发事件;--><!-- 准备好一个容器--><div id="root"><h2>欢迎来到{{name}}学习</h2><!-- 阻止默认事件(常用) --><a href="" @click.prevent="showInfo">点我提示信息</a><!-- 阻止事件冒泡(常用) --><div class="demo1" @click="showInfo"><button @click.stop="showInfo">点我提示信息</button><!-- 修饰符可以连续写 先写的先起作用: 这样写就是先阻止默认行为后阻止冒泡--><!-- <a href="" @click.prevent.stop="showInfo">点我提示信息</a> --></div><!-- 事件只触发一次(常用) --><button @click.once="showInfo">点我提示信息</button><!-- 使用事件的捕获模式 --><div class="box1" @click.capture="showMsg(1)">div1<div class="box2" @click="showMsg(2)">div2</div></div><!-- 只有event.target是当前操作的元素时才触发事件; --><div class="demo1" @click.self="showInfo"><button @click="showInfo">点我提示信息</button></div></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el: '#root',data: {name: '尚硅谷'},methods: {showInfo(e) {alert('同学你好!')// console.log(e.target)},showMsg(msg) {console.log(msg)}}})</script></html>

1.1 prevent:阻止默认事件(常用)

html:

<!-- 阻止默认事件(常用) --><a href="" @click.prevent="showInfo">点我提示信息</a>

js:

运行效果:

a标签的默认有跳转到href的行为,我们把默认行为禁用后,就不会跳转页面

补充:

如果不使用Vue指令,那么怎么屏蔽事件的默认行为呢?

1.2 stop:阻止事件冒泡(常用)

html:

<!-- 阻止事件冒泡(常用) --><div class="demo1" @click="showInfo"><button @click.stop="showInfo">点我提示信息</button><!-- 修饰符可以连续写 --><!-- <a href="" @click.prevent.stop="showInfo">点我提示信息</a> --></div>

js:

运行结果:

如果不组织事件冒泡:

如果不使用Vue指令,那么怎么阻止事件冒泡呢?

1.3 once:事件只触发一次(常用)

html:

<!-- 事件只触发一次(常用) --><button @click.once="showInfo">点我提示信息</button>

js:

运行结果:

1.4 capture:使用事件的捕获模式

html:

<!-- 使用事件的捕获模式 --><div class="box1" @click.capture="showMsg(1)">div1<div class="box2" @click="showMsg(2)">div2</div></div>

js:

运行结果:

关闭事件捕获:

分析原因:

1.5 self:只有event.target是当前操作的元素时才触发事件

html:

<!-- 只有event.target是当前操作的元素时才触发事件; --><div class="demo1" @click.self="showInfo"><button @click="showInfo">点我提示信息</button></div>

js:

运行结果:

因为event.target不是当前操作的元素,所有没有触发事件,这个在一定程度上面也可以阻止冒泡

如果不加指令会怎么样?

发生了事件冒泡

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。