Vue中的v-系列(自用-2)

44 阅读1分钟

三、v-on

给元素绑定事件监听器。

  • 缩写: @
  • 期望的绑定值类型: Function | Inline Statement | Object (不带参数)
  • 参数: event (使用对象语法则为可选项)
  • 修饰符
    • .stop - 调用 event.stopPropagation()
    • .prevent - 调用 event.preventDefault()
    • .capture - 在捕获模式添加事件监听器。
    • .self - 只有事件从元素本身发出才触发处理函数。
    • .{keyAlias} - 只在某些按键下触发处理函数。
    • .once - 最多触发一次处理函数。
    • .left - 只在鼠标左键事件触发处理函数。
    • .right - 只在鼠标右键事件触发处理函数。
    • .middle - 只在鼠标中键事件触发处理函数。
    • .passive - 通过 { passive: true } 附加一个 DOM 事件。

例子:

<template>
  <div>
    <!-- 基本点击事件,function函数 -->
    <button v-on:click="handleClick">点击我</button>
    
    <!-- 缩写形式 -->
    <button @click="handleClick">点击我</button>
    
    <!-- 内联语句 -->
    <button @click="count++">计数: {{ count }}</button>
    
    <!-- 传递参数 -->
    <button @click="sayHello('Vue')">打招呼</button>
    
    <!-- 访问原生事件 -->
    <button @click="handleEvent($event)">访问事件对象</button>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const count = ref(0)

const handleClick = () => {
  alert('按钮被点击了!')
}

const sayHello = (name) => {
  alert(`Hello, ${name}!`)
}

const handleEvent = (event) => {
  console.log('事件类型:', event.type)
  console.log('目标元素:', event.target)
}
</script>

复习:

1.${} - 插值表达式
const name = 'Alice'
const age = 25

// 变量插值
`Hello, ${name}!`                    // "Hello, Alice!"

// 表达式计算
`Next year you will be ${age + 1}`   // "Next year you will be 26"

// 函数调用
`Current time: ${new Date()}`        // "Current time: Thu Dec 07 2023 ..."

// 三元运算符
`Status: ${age >= 18 ? 'Adult' : 'Minor'}`  // "Status: Adult"
2.$event用于在模板中访问原生 DOM 事件对象
  <!-- $event 代表原生的 DOM 事件对象 -->
  <button @click="handleEvent($event)">点击我</button>
</template>

<script setup>
const handleEvent = (event) => {
  console.log(event)           // 原生 Event 对象
  console.log(event.type)      // "click"
  console.log(event.target)    // 按钮元素
  console.log(event.clientX)   // 点击的 X 坐标
}
</script>