1
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?

[Vue] コンポーネント イベントの発行

1
Posted at

Vue公式のチュートリアル
イベントの発行

これは初めて知ったかも・・。

props を受け取るだけでなく、子コンポーネントは親コンポーネントにイベントを発行することもできます:

child側
<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としてみたけど、ちゃんと動いた。

child側
<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で書いた。

1
0
0

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
1
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?