我们可以使用v-on来监听DOM事件,并在事件触发时执行对应的Vue的Javascript代码。
- 用法:v-on:click = "handler" 或简写为 @click = "handler"
- vue中的事件名=原生事件名去掉 on 前缀 如:onClick --> click
- handler的值可以是方法事件处理器,也可以是内联事件处理器
- 绑定事件时,可以通过一些绑定的修饰符,常见的事件修饰符如下
|--------------------------------|
| @click.once:只触发一次事件。重点 |
| @click.prevent:阻止默认事件。重点 |
| @click.stop:阻止事件冒泡 |
| @click.capture:使用事件捕获模式而不是冒泡模式 |
| @click.self:只在事件发送者自身触发时才触发事件 |
html<script setup> import {ref} from "vue"; //响应式数据 当发生变化时,会自动更新 dom 树 let count = ref(0); let addCount=()=>{ count.value++; } let incrCount=(event)=>{ count.value++; //通过事件对象阻止组件的默认行为 event.preventDefault(); } let sayHello=()=>{ alert("hello world!") } let h01=()=>{ alert("ho1") } let h02=()=>{ alert("ho2") event.stopPropagation(); //阻止事件传播,繁殖,蔓延 } let h03=()=>{ alert("h03"); } </script> <template> <div> <h1>count的值是:{{count}}</h1> <!--方法事件处理器--> <button v-on:click="addCount()">addCount</button><br> <!--内联事件处理器--> <button @click="count++">incrCount</button><br> <!--事件修饰符 once 只绑定事件一次--> <button @click.once="count++">addOnce</button><br> <!--事件修饰符 prevent 阻止组件的默认行为--> <a href="https://blog.csdn.net/m0_65152767?spm=1011.2124.3001.5343" target="_blank" @click.prevent="count++">prevent</a><br> <!--原是js方式阻止组件默认行为(推荐)--> <a href="https://blog.csdn.net/m0_65152767?spm=1010.2135.3001.5343" target="_blank" @click="incrCount($event)">prevent</a><br> <button v-on:click="sayHello">点我</button> <button @click="sayHello">点我省略v-on:</button> <div @click="h01" style="background-color: #abc;width: 200px;height: 200px"> <div @click="h02" style="background-color: #cba;width: 100px;height: 100px">HELLO</div> <div @click.stop="h03" style="background-color: #dfb;width: 100px;height: 100px">HELLO</div> </div> </div> </template>
Vue3+Vite实现工程化,事件绑定以及修饰符
丁总学Java2023-11-20 11:42
相关推荐
LinXunFeng3 小时前
Obsidian - 使用 Share Note 分享笔记并自部署乘风gg6 小时前
为什么AI 时代来临,大部分人吃不到红利恋猫de小郭7 小时前
Android 限制侧载新进展,谷歌联合国内厂商推验证计划IT_陈寒7 小时前
Redis内存爆了,原来我漏掉了这个致命配置恋猫de小郭7 小时前
解读 Android 17 全新内存限制,有没有“豁免”后门?Hyyy8 小时前
理解LLM的基本工作原理:预训练、微调、推理的区别Gatlin9 小时前
前端逆向与反逆向:一场猫鼠游戏的底层逻辑与实战代码煮茶9 小时前
React 组件封装方法论 —— 以 Todo App 为例Pedantic9 小时前
本地通知(Local Notifications)学习笔记任沫9 小时前
Agent之Function Call