Vue.js

#3 Vue.js基礎(v-on)

kurumin

イベントリスナを設定するv-on

HTMLタグにイベントリスナを設定するには、v-onディレクティブを使用する。

<script setup lang="ts">
import { ref } from "vue";

const randValue = ref("まだです");
const onButtonClick = (): void => {
  const rand = Math.round(Math.random() * 10);
  randValue.value = String(rand);
};
</script>

<template>
  <section>
    <button v-on:click="onButtonClick">クリック!</button>
    <p>クリックの結果:{{ randValue }}</p>
  </section>
</template>
v-on
v-on:イベント名="イベント発生時に実行するメソッド名"
メソッドの定義
const メソッド名 = (): void => {
  処理内容
};

v-onディレクティブは省略形もあるが、可読性の観念で非推奨。

<button @click="onButtonClick">クリック!</button>
数値の文字列の変換
randValue.value = String(rand);

上記のコードについて、次のように記述するとエラーになる。

randValue.value = rand;

TypeScriptでは、データ型を厳密に扱う。

randは乱数なので数値型になる。
一方、randValueの元となるref()に渡した値は文字列なので、randValue.valueも文字列。
文字列型変数に数値は代入できないためエラーが発生する。

v-onのイベント

v-onディレクティブの引数として記述するイベント名には、JavaScriptで用意されているイベント名を記述する。

メソッドの引数としてイベントオブジェクトを受け取る

v-onディレクティブに対応したイベントハンドラメソッドは、イベントオブジェクトを引数として受け取ることができる。

<script setup lang="ts">
import { ref } from "vue";

const mousePointerX = ref(0);
const mousePointerY = ref(0);

const onImgMousemove = (event: MouseEvent): void => {
  mousePointerX.value = event.offsetX;
  mousePointerY.value = event.offsetY;
}
</script>

<template>
  <section>
    <img src="./assets/logo.svg" alt="Vueのロゴ" width="200" v-on:mousemove="onImgMousemove">
    <p>ポインタの位置: x={{ mousePointerX }}; y={{ mousePointerY }}</p>
  </section>
</template>
(event: MouseEvent)

引数としてeventを用意し、その引数の型としてMouseEventを指定している。

イベントオブジェクト以外を引数とするイベントハンドラメソッド

イベントオブジェクトではなく任意の引数を受け取る場合は、引数をテンプレートブロックで渡す必要がある。

<script setup lang="ts">
import { ref } from "vue";

const pBgColor = ref("white");
const onPClick = (bgColor: string): void => {
  pBgColor.value = bgColor;
};
</script>

<template>
  <section>
    <p v-on:click="onPClick('red')" v-bind:style="{ backgroundColor: pBgColor }">ここをクリックすると背景色が変わります。</p>
  </section>
</template>

イベントオブジェクトとその他の引数を併用するイベントハンドラメソッド

<script setup lang="ts">
import { ref } from "vue";

const pMsg = ref("イベント前(ここをクリック!)");
const pBgColorEvent = ref("white");
const onPClickWithEvent = (bgColor: string, event: MouseEvent): void => {
  pBgColorEvent.value = bgColor;
  pMsg.value = event.timeStamp.toString();
}
</script>

<template>
  <section>
    <p v-on:click="onPClickWithEvent('green', $event)" v-bind:style="{ backgroundColor: pBgColorEvent }">{{ pMsg }}</p>
  </section>
</template>
$event

引数を省略したときはイベントオブジェクトを自動的に引数として渡してくれるが、他の引数と組み合わせる場合は引数部分でイベントオブジェクトとして$eventを明記する必要がある。

v-onの修飾子

prevent修飾子

入力コントロールをformタグで囲み、ボタンのtypeをsubmitとする必要がある。

<script setup lang="ts">
import { ref } from "vue";

const msg = ref("未送信");
const onFormSubmit = (): void => {
  msg.value = "送信されました。";
};
</script>

<template>
  <form action="#" v-on:submit.prevent="onFormSubmit">
    <input type="text" required>
    <button type="submit">送信</button>
  </form>
  <p>{{ msg }}</p>
</template>
v-on:submit.prevent=”onFormSubmit”

v-on:submit=”onFormSubmit”と記述した場合、onFormSubmitメソッドが実行された直後に本来のサビミットイベントも実行されてaction属性に指定されたURLが呼び出されてしまう。このような本来のイベントをキャンセルするのが.prevent修飾子である。

このprevent修飾子は、JavaScript標準のpreventDefault()メソッドを呼び出すことで実現されている。

passive修飾子

preventDefault()メソッドを実行しないことをブラウザに通知するもの。
passive修飾子はprevent修飾子の働きとも言える。
.passiveを付けることにより、ブラウザが即座にイベント処理を行えるようになる。
例えば、この.passiveをscrollイベントに適用すると、スクロール処理が即座に実行されるようになり、モバイル環境でのスクロールのカクツキを軽減できる。

クリックイベントとキーイベントの修飾子

v-onディレクトリの修飾子のうち、クリックイベントとキーイベントには、専用の修飾子が用意されている。必要に応じて調べる。

<script setup lang="ts">
import { ref } from "vue";

const msg = ref('まだです!');
const onEnterKey = (): void => {
  msg.value = "エンターキーが押下されました。";
};
const onRightButtonClick = (): void => {
  msg.value = "ボタンが右クリックされました。";
};
const onShiftClick = (): void => {
  msg.value = "シフトを押しながらクリックされました。";
};
</script>

<template>
  <p>{{ msg }}</p>
  <input type="text" v-on:keydown.enter="onEnterKey"><br>
  <button v-on:click.right="onRightButtonClick">右クリック</button><br>
  <button v-on:click.shift="onShiftClick">シフトを押しながらクリック</button>
</template>

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