vue3 事件处理 @click

一、基本使用

<template>
    <!--直接通过js代码处理-->
    <p @click="counter++">{{"直接使用:"+counter}}</p>
    <!--函数分离-->
    <p @click="addCounter0">{{"函数分离:"+counter}}</p>
    <!--传入参数-->
    <p @click="addCounter1(5)">{{"传入参数:"+counter}}</p>
    <!--事件对象-->
    <p @click="addCounter2(6,$event)">{{"事件对象:"+counter}}</p>
    <!--多个函数-->
    <p @click="addCounter0(),addAge()">{{"多个函数:"+counter}}--{{age}}</p>
</template>

<script setup>
import { ref, reactive } from 'vue'
const counter=ref(0)
const age=ref(3)

function addCounter0(){
    counter.value++
}

function addCounter1(num){
    counter.value+=num
}

function addCounter2(num,e){
    counter.value+=num
    console.log("事件对象:",e)
}

function addAge(){
    age.value++
}
</script>

传入多个函数,函数需要带上括号()

二、事件修饰

2.1 stop阻止事件冒泡

<template>
    <div @click="divClick">
        <button @click.stop="btnClick">按钮</button>
    </div>
</template>

<script setup>
function divClick(){
    console.log("父div事件")
}

function btnClick(){
    console.log("子btn事件")
}

</script>

无stop:会触发 btnClick,再触发divClick
有stop:只触发btnClick

2.2 prevent阻止默认行为

<form action="">
    <input type="submit" value="提交" @click.prevent="submitClick">
</form>

2.3 once只触发一次回调

<button @click.once="btnClick">触发一次</button>

三、按键修饰

按下对应按钮,会触发对应事件

<template>
    <input type="text" @keyup.enter="btnClick" />
</template>

<script setup>
function btnClick(){
    console.log("子btn事件")
}
</script>

常用的按键

按键解释
enter回车
tab切换
delete删除
esc退出
space空格
up向上
down向下
left向左
right向右
Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐