腾讯企点客户通seo网络推广公司排名
一.事件处理
事件修饰符
Vue通过由点(.)表示的指令后缀来调用修饰符, .stop, .prevent,.capture,.self,.once
.stop
:阻止事件冒泡。当一个元素触发了事件,并且该元素包含嵌套的父元素时,使用.stop
修饰符可以防止事件被传递到祖先元素。
.prevent
:阻止默认事件。当一个元素上触发了某个事件,使用.prevent
修饰符可以阻止浏览器执行默认的事件行为。
.capture
:使用事件捕获模式。默认情况下,Vue中的事件监听器是通过事件冒泡模式处理的,即从子元素冒泡到父元素。但是使用.capture
修饰符可以将事件监听器绑定到捕获阶段,即从父元素捕获到子元素。
.self
:只当事件在指定元素自身触发时触发。当一个元素包含子元素,并且绑定了相同的事件处理函数时,使用.self
修饰符可以确保事件只在元素自身触发时才执行处理函数。
.once
:只触发一次事件。当绑定了.once
修饰符的事件被触发后,监听器将自动解绑,以确保处理函数只执行一次。
代码演示:
<!DOCTYPE html>
<html><head><meta charset="utf-8"><script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script><title>事件处理</title><style type="text/css">.one{background-color: red;height: 400px;width: 400px;} .two{background-color: yellow;height: 300px;width: 300px;} .three{background-color: pink;height: 200px;width: 200px;} .four{background-color: green;height: 100px;width: 100px;}</style></head><body><div id="app"><div class="one" @click="fun1"><div class="two" @click="fun2"><div class="three" @click="fun3"><div class="four" @click.stop="fun4"></div></div></div></div><input :value="msg"/><button @click="clickme">点我</button><form @submit.prevent="submitForm"><button type="submit">提交</button></form><div @click.capture="parentClick"><button @click="childClick">点击我</button></div><div @click.self="parentClick"><button @click="childClick">点击我</button></div></div><script type="text/javascript">new Vue({el:'#app',data(){return {msg:'你好'};},methods:{fun1(){alert("fun1")},fun2(){alert("fun2")},fun3(){alert("fun3")},fun4(){alert("fun4")},clickme(){console.log(this.msg)},submitForm() {console.log("表单提交事件");},parentClick() {console.log("父元素点击事件");},childClick() {console.log("子元素点击事件");}}})</script></body>
</html>
效果: