LoginSignup
0
0

More than 3 years have passed since last update.

【Vue.js】コンポーネント $emit で 子 → 親 へデータを渡す

Last updated at Posted at 2020-07-13

はじめに

$emitを使ったコンポーネント親子間のデータのやりとりがなかなかややこしく感じた。
なのでやったことを記録に残します。

$emit とは?
Vue.js リファレンス を読んでも正直よくわかりませんでした。
この親子間のデータのやりとりに関しては、
「子コンポーネントで指定したタイミングに、親コンポーネントで処理を起こさせることができる。その処理ついでにデータを渡す。」

みたいな感じで勝手に解釈しました。(わかりずらくてすみません)

どんなものを実装するか?

・子コンポーネントにボタンを設置。
・そのボタンをクリックすると親コンポーネントのdataの値(初期値0)に1加算された値が子コンポーネントから送られる。

実装してみる

Child.vue
<template>
  <!-- クリックでplus1メソッドを呼び出す -->
  <button @click="plus1">プラス1</button>
</template>

<script>
export default {
  props: ["childScore"],
  methods: {
    plus1() {
      // $emit('親コンポーネントで発火させる関数の名前', 処理の内容);
      this.$emit('plus-click', this.childScore + 1);
    }
  }
}
</script>
Parent.vue
<template>
  <!-- :child-score="score" で初期値を渡している。 -->
  <!-- そして@plus-clickイベントが発火したら、$event($emitで発火させたplus1メソッド処理後の値)をscoreに代入する -->
  <Child :child-score="score" @plus-click="score = $event"></Child>
  <p>{{ score }}</p>
</template>

<script>
import Child from "Child.vue"

export default {
  data() {
    return {
      score: 0,
    }
  }
}
</script>

最後に

props, $emit などコンポーネント間のデータやりとりなかなか難しい。
間違いなどなどあれば、気軽にご指摘ください。

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