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?

More than 1 year has passed since last update.

Vue3 / Nuxt3 – 子コンポーネントのカウントを合算して親コンポーネントに表示する、リセットする

Last updated at Posted at 2023-01-27

無理矢理な実装かもしれないのでもっと良い方法があるかも

要点

  • 親では配列としてカウンタの値の器を複数持っておく
  • 子では対応する親のカウンタ値を直接カウントアップする
  • 親では全カウンタの合算値を表示する

親 ( IncrementParent.vue )

<!-- https://teratail.com/questions/k9a3uom29j319c -->

<template>
  <div>
    <div>
      Total Count
      {{ totalCount }}
    </div>
    <button @click="reset">Reset</button>

    <div v-for="numbering in numberings" v-bind:key="numbering">
      <CountupChild :numbering="numbering"></CountupChild>
    </div>
  </div>
</template>

<script>
import CountupChild from '../components/CountupChild.vue'

const countupLoop = 3; // 子コンポーネントを作る数
const defaultNumbers = [...Array(countupLoop)].map((_, i) => 0); // [0,0,0] のような初期値

export default {
  data() {
    return {
      numbers: defaultNumbers,
      numberings: [...Array(countupLoop)].map((_, i) => i)
    }
  },
  // カウンターの値を全て合算
  computed: {
    totalCount: function () {
      return this.numbers.reduce(function (sum, element) {
          return sum + element;
        }, 0)
    }
  },
  methods: {
    reset() {
      this.numbers = [...Array(countupLoop)].map((_, i) => 0)
    }
  },
  components: {
    CountupChild
  }
}
</script>

子 ( CountupChild.vue )

<template>
  <div>
    <p>Count ({{ $parent.numbers[this.numbering] }})</p>
    <button @click="increment">+1</button>
  </div>
</template>
<script>
export default {
  props: {
    numbering: {
      type: Number,
    }
  },
  methods: {
    increment() {
      this.$parent.numbers[this.numbering] += 1;
    },
  }
}
</script>

動作例

子のカウントアップの合計値が親に表示されている

image.png

リセットすると全てゼロになる

image.png

環境

  • nuxt@3.0.0

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?