发布于 

Vue 中的特殊变量 $event

根据 Vue 文档,在 Vue 中进行事件监听时,事件的回调函数有两种写法:

  1. 接受方法名:不带圆括号的形式不需要传参,event 对象将被自动当做实参传入。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <template>
    <button @click="greet">Greet</button>
    </template>

    <script setup>
    const greet = (event) => {
    console.log(event) // event 对象
    }
    </script>
  2. 接受对某个方法的调用:带圆括号的形式可以传参,打印出来的 event 将会变成我们手动传递的那个参数。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <template>
    <button @click="greet(233)">Greet</button>
    </template>

    <script setup>
    const greet = (event) => {
    console.log(event) // 233
    }
    </script>

如果现在既需要传递参数,又需要用到 event 对象,该如何做呢?

这时候就需要用到 $event 这个特殊的变量啦,在内联声明的写法中,我们需要把 $event 变量作为参数,显式地传入方法中。

1
2
3
4
5
6
7
8
9
10
<template>
<button @click="greet($event, 233)">Greet</button>
</template>

<script setup>
const greet = (event, x) => {
console.log(event) // event 对象
console.log(x) // 233
}
</script>

自定义事件中的 $event

定义了一个子组件 MyButton,并给 $emit 提供一个额外的参数。

1
2
3
<button @click="$emit('increaseBy', 1)">
Increase by 1
</button>

通常用一个组件方法来作为事件处理函数,该方法会接收到事件所传递的参数。

1
2
3
4
5
6
7
8
9
10
<template>
<MyButton @increase-by="increaseCount" />
</template>

<script setup>
const count = ref(0)
function increaseCount(n) {
count.value += n
}
</script>

当需要给 increaseCount 函数额外传递参数时,也可以使用 $event,此时的 $event 就是事件附带的参数。

1
2
3
4
5
6
7
8
9
10
11
<template>
<MyButton @increase-by="increaseCount($event, 233)" />
</template>

<script setup>
const count = ref(0)
function increaseCount(n, x) {
count.value += n
console.log(x) // 233
}
</script>

(●'◡'●)ノ♥