LoginSignup
1
1

More than 1 year has passed since last update.

【Vue2】孫から親コンポーネントへのデータの受け渡しを簡単に行う

Last updated at Posted at 2023-03-23

概要

孫コンポーネントから親コンポーネントにデータを渡したい状況って結構な頻度であると思います。
今回はcomposition apiでやっていますが、

何も考えずに書くとこんな感じ

parent.vue
<template>
    <Button @update="update">
</template>

<script>
    update(value) {
      console.log(value)
    }
</script>
child.vue
<template>
    <Button @update="update">
</template>

<script>
    update(value) {
    	this.$emit('update', value);
    }
</script>
grandchild.vue
<template>
    <Button @update="update">
</template>

<script>
    update(value) {
    	this.$emit('update', value);
    }
</script>

ですが、このコンポーネントの階層がさらに深くなったとしたら、とてもじゃないけど、追いきれません。
絶対にもっと簡単にする方法があるやろってことで調べていたら、やっぱりありました。

解決方法

$listenersというものを使います。
親と最後の孫以外の挟まれているコンポーネントで使うことで無駄な記述がかなり減らせます!

parent.vue
<template>
    <Button @update="update">
</template>

<script>
    update(value) {
      console.log(value)
    }
</script>
child.vue
<template>
    <Button @update="$listeners['update']">
</template>

<script>
// ここで行なっていたemit処理が不要になる
</script>
grandchild.vue
<template>
    <Button @update="update">
</template>

<script>
    update(value) {
    	this.$emit('update', value);
    }
</script>

補足

ちなみにvue3では$listenersはなくなり、$attrsというものになるみたいです。
https://v3-migration.vuejs.org/breaking-changes/listeners-removed.html

参考

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