Vue3+Vite实现工程化,事件绑定以及修饰符

我们可以使用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>
相关推荐
IT_陈寒2 分钟前
Java的HashMap竟然不是线程安全的,现在才知道!
前端·人工智能·后端
IT_陈寒2 分钟前
React hooks闭包陷阱让我加了一宿班
前端·人工智能·后端
mONESY3 分钟前
给大模型装上记忆:Agent 的 Memory 模块,从 InMemory 到文件到 Milvus 向量数据库
javascript
不一样的少年_3 分钟前
设计稿里的图片明明很清晰,为什么到了手机上却糊了?一文讲透 DPR、压缩与格式选择
前端·后端·图片资源
计算机魔术师4 分钟前
OpenAI内部数据曝光:AI已经替人类写了3.1倍的研究代码
前端
心易行者7 分钟前
用html在线运行做数据可视化大屏,5个实战场景从入门到上线
大数据·前端·数据库·人工智能·python
橘子星7 分钟前
给 Agent 装上有记忆的"脑子"(一):用 LangChain 打通内存记忆、文件持久化与上下文截断
javascript
光影少年7 分钟前
从输入URL到页面渲染,React/RN 整体加载流程
前端·javascript·react native·react.js·前端框架
兔子零10249 分钟前
我给 Pi Coding Agent 做了一个桌面控制台:Pi-Harness
前端·javascript·后端
Kevin Coding10 分钟前
鸿蒙 emitter/EventHub 没有 Sticky 粘性事件?手写一个轻量级 EmitterManager 解决
前端·华为·前端框架·移动开发·harmonyos