v-onの修飾子 Modifiers

date
Mar 4, 2023
repo_url
slug
von-param-both-event
status
Published
summary
type
Post
thumbnail_url
tags
vue
outer_link
修飾子(Modifiers)とは、引数のあとに”.(ドット)”でつないで記述するキーワードのこと。

prevent修飾子

特に何も修飾子を付けていない以下の例では、
①v-on:submitのonFormSubmitが実行
②本来のサブミットイベントが実行(action属性のURLが呼出し)
となってしまう。
<script setup lang="ts">
import { ref } from 'vue';

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

<template>
  <form action="https://www.google.com/" v-on:submit="onFormSubmit">
    <input type="text" required />
    <button type="submit">送信</button>
  </form>
  <p>{{ msg }}</p>
</template>
.prevent修飾子をつけると、本来のサブミットイベントがキャンセルされる。
<script setup lang="ts">
import { ref } from 'vue';

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

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

passive修飾子

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

© Hayato Kamiyama 2023 - 2024 - Build with Next.js & Notion