Vue.js

Vue.jsのイベントオブジェクトとイベントハンドラ

kurumin

イベントハンドラの書き方

インラインで書く方法と、関数で書く方法がある。

<script setup>
import { ref } from 'vue'
let count = ref(0)
function countUp(event) {
  count.value = event.clientX
}
</script>

<template>
  <p>{{ count }}</p>
  <button @click="count = $event.clientX">クリック</button>
  <button @click="countUp">クリック</button>
</template>

インラインの場合、$eventの中にイベントの情報が入る。

関数の場合、第一引数にイベントの情報が入る。

関数に引数を渡したい場合

インライン記法で書く。

<script setup>
import { ref } from 'vue'
let count = ref(0)
function countUp(event, times) {
  count.value = event.clientX * times
}
</script>

<template>
  <p>{{ count }}</p>
  <button @click="countUp($event, 5)">クリック</button>
</template>

$eventは明示的に第一引数に記述する必要がある。

ABOUT ME
記事URLをコピーしました