Vue公式のチュートリアル
イベントの発行
これは初めて知ったかも・・。
props を受け取るだけでなく、子コンポーネントは親コンポーネントにイベントを発行することもできます:
<script setup>
// 発行されるイベントを宣言します
const emit = defineEmits(['response'])
// 引数つきで発行
emit('response', 'hello from child')
</script>
emit() の第一引数はイベント名です。追加の引数は、イベントリスナーに渡されます。
親は v-on を使って子が発行するイベントを購読できます。ここでは、ハンドラーは子の emit 呼び出しから追加の引数を受け取り、それをローカルステートに割り当てています:
<ChildComp @response="(msg) => childMsg = msg" />
この @response って、一体、何を意味しているのか全然分からなかったけど・・・。
@clickとかはよく見るけど。。
そもそも、@clickは省略形で、
v-on:click="handler"、を省略して @click="handler"
と書くと。
なので、
@response は、略さず書くと、v-on:response なのね。
で、
@click とかは、特に自分で定義しなくても使えたけど、
今回、emit で、response という名前のイベントを定義しているので、
@response で呼べるようになったということのようだ。
だから、
emit で、response1 という名前で定義すると、@response1 で呼ぶことになる。
以下、responseをresponse1としてみたけど、ちゃんと動いた。
<script setup>
// 発行されるイベントを宣言します
const emit = defineEmits(['response1'])
// 引数つきで発行
emit('response1', 'hello from child')
</script>
<script setup>
import { ref } from 'vue';
import ChildComp from './ChildComp.vue';
const childMsg = ref('No child msg yet');
</script>
<template>
<ChildComp @response1="(msg) => (childMsg = msg)" />
<p>{{ childMsg }}</p>
</template>
stackblitzで書いた。