Home > Blockchain >  Problem with emitting from 2 child components into 1 parent component
Problem with emitting from 2 child components into 1 parent component

Time:08-10

I'm emitting a value (which is always 1 or -1) to parent component, everytime a click event happens in child component.

When i press click events from only one child component, i'm getting the value as it should be. But when i start pressing from other component too, total value resets. I need total to not reset and keep increasing or reducing with the value*2 operation all the way no matter which component i press from.

How can i block this value reset when i start pressing from other child component?

<!-- here is Parent Component. -->

<script setup>

import ChildComp1 from "./ChildComp1.vue";
import ChildComp2 from "./ChildComp2.vue";
import { ref } from "vue";

const total =ref(0);

</script>

<!-- Now inserting 2 ChildComps to template:  -->

<template>
  <div>

<ChildComp1
       @increment="(value) => (total = value * 2)"
       @reduce="(value) => (total = value * 2)"
   />

<ChildComp2
       @increment="(value) => (total = value * 2)"
       @reduce="(value) => (total = value * 2)"
   />

    <h3><span>Total:</span> ${{ total }}.00</h3>

  </div>
</template>
<!--  and here is the childcomps, they are same so i share only 1 code --> 

<script setup>

import { ref } from "vue";

const amount = ref(0);

</script>

<template>
  <div>
    <div >
      <button
        
        @click="amount--, $emit('reduce', amount)"
      ></button>
      <p >{{ amount }}</p>
      <button
        
        @click="amount  , $emit('increment', amount)"
      ></button>
    </div>
  </div>
</template>

CodePudding user response:

When you send the value from the second child component which equals to 0 will reset the total since 0*2=0, try to reassign the total using = or -= operators :

<ChildComp1
       @increment="(value) => (total  = value * 2)"
       @reduce="(value) => (total -= value * 2)"
   />

<ChildComp2
       @increment="(value) => (total  = value * 2)"
       @reduce="(value) => (total -= value * 2)"
   />

CodePudding user response:

i found the solution by making 1 more change onto @Boussadjra Brahim's answer.


<!-- after implementing operator changes on parent component: -->

<!-- ParentComp -->

<ChildComp1
      @increment="(value) => (total  = value * 2)"
      @reduce="(value) => (total -= value * 2)"
    />
<ChildComp2
      @increment="(value) => (total  = value * 2)"
      @reduce="(value) => (total -= value * 2)"
    />



<!--  I needed to make one more change on child components; we are 
not emitting the "amount", we emit just 1 --> 

<!-- ChildComp -->

<div >
        <button  @click="amount--, $emit('reduce', 1)">
          <img  src="../ico/arrow.svg" />
        </button>
        <p >{{ amount }}</p>
        <button  @click="amount  , $emit('increment', 1)">
          <img  src="../ico/arrow.svg" />
        </button>
      </div>
  • Related