Vue - 事件处理详解

组件代码

下面是一个基本的 Vue.js 组件代码,其中包含了不同类型的事件处理器:

<template>
  <div>
    <!-- 内联事件处理器:点击按钮时调用 increaseCount 方法 -->
    <button @click="increaseCount">加 1</button>
    <p>计数为: {
  { count }}</p>

    <!-- 方法事件处理器:点击按钮时调用 greet 方法 -->
    <button @click="greet">打招呼</button>

    <!-- 在内联事件处理器中调用方法:点击按钮时调用 say 方法 -->
    <button @click="say('你好')">说你好</button>
    <button @click="say('再见')">说再见</button>

    <!-- 在内联事件处理器中访问事件参数:点击按钮时调用 warn 方法 -->
    <button @click="warn('表单目前无法提交。', $event)">提交</button>
    <button @click="(event) => warn('表单目前无法提交。', event)">提交</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      count: 0,
      name: "Vue.js"
    };
  },
  methods: {
    // 方法事件处理器:打招呼方法
    greet(event) {
      alert(`你好 ${this.name}!`);
      if (event) {
        alert(event.target.tagName);
      }
    },

    // 在内联事件处理器中调用方法:接收消息参数并弹出提示框
    say(message) {
      alert(message);
    },

    // 在内联事件处理器中访问事件参数:阻止默认提交行为并弹出警告
    warn(message, event) {
      if (event) {
        event.preventDefault();
      }
      alert(message);
    },

    // 内联事件处理器:增加计数方法
    increaseCount() {
      this.count++;
    }
  }
};
</script>

内联事件处理器

内联事件处理器是一种简单而直接的处理事件的方式。在上述代码中,我们使用 @clickv-on:click 来监听按钮的点击事件,并调用相应的方法。例如,@click="increaseCount" 表示点击按钮时调用 increaseCount 方法来增加计数。

方法事件处理器

当事件处理逻辑变得更为复杂时,可以使用方法事件处理器。在上述代码中,我们定义了 greetsaywarn、和 increaseCount 方法,然后通过 @click 直接引用这些方法。这使得代码更加模块化和易于维护。

事件参数和修饰符

Vue.js 允许我们访问原生 DOM 事件及其参数。例如,通过 $event 变量,我们可以在 warn 方法中访问原生 DOM 事件,并阻止其默认行为。同时,Vue.js 提供了事件修饰符,如 .stop.prevent.self 等,用于简化事件处理的常见需求。

相关推荐

  1. Vue - 事件处理详解

    2023-12-30 10:28:03       39 阅读
  2. vue3--事件处理

    2023-12-30 10:28:03       19 阅读
  3. vue 事件处理

    2023-12-30 10:28:03       22 阅读
  4. Vue2事件处理

    2023-12-30 10:28:03       11 阅读
  5. 前端vue2学习(事件处理)总结

    2023-12-30 10:28:03       17 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-30 10:28:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-30 10:28:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-30 10:28:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-30 10:28:03       20 阅读

热门阅读

  1. Docker搭建kafka集群

    2023-12-30 10:28:03       32 阅读
  2. 如何在Vue.js中使用$emit进行组件通信

    2023-12-30 10:28:03       36 阅读
  3. leetcode贪心(最大子序列和、分发饼干、摆动序列)

    2023-12-30 10:28:03       32 阅读
  4. uboot学习及内核更换_incomplete

    2023-12-30 10:28:03       52 阅读
  5. 【小白专用】c# 如何获取项目的根目录

    2023-12-30 10:28:03       41 阅读
  6. Unity应该如何学

    2023-12-30 10:28:03       36 阅读
  7. uniapp学习之路

    2023-12-30 10:28:03       37 阅读
  8. 2023年度最后一天班

    2023-12-30 10:28:03       38 阅读