0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

defineEmitsに引数を与える

Last updated at Posted at 2025-02-11

defineEmitsとは

子コンポーネントから親コンポーネントの関数を実行する。

例)

  1. 子コンポーネントのボタンをクリック
  2. 親コンポーネントでメッセージを表示
<!-- 子コンポーネント ButtonComponent -->
<template>
  <button type="button" class="btn btn-success" @click="$emit('pushbutton')">
    ボタン
  </button>
</template>

<script setup lang="ts">
const emit = defineEmits(["pushbutton"]);
</script>

子コンポーネントにpushbuttonイベントを定義して、親コンポーネント側でハンドラー関数を紐づける。

<!-- 親コンポーネント -->
<template>
  <div>
    <ButtonComponent @pushbutton="handlePushButton('なんかのメッセージ')" />
    {{ buttonMessage }}
  </div>
</template>

<script setup lang="ts">
const buttonMessage = ref("")

// 子コンポーネントから呼ばれる関数
const handlePushButton = (msg: string) => {
  buttonMessage.vue = msg;
};
</script>

引数を持っていることを明示したい

親コンポーネントから引数を与える場合は、最初の例のように引数の定義がなくても問題ない。
これが気持ち悪いので子コンポーネント側で引数の型情報を与えても、子コンポーネント側で引数を矯正されるだけで親コンポーネント側で引数があることはわからない。

チェックしたい場合はどこかに型を定義して親コンポーネントと子コンポーネントで共有する必要がある。

<script setup lang="ts">
const emit = defineEmits<{
  (e: "pushbutton", msg: string): void;
}>();
</script>
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?