Search code examples
vue.jsvuejs2vuejs3vue-componentpinia

Why don't works emits?


I recently started learning Vue and ran into a very strange and incomprehensible problem for me. I do not argue that from the point of view of the architectural approach, this code may be wrong, but still I want to understand the logic. I have four components HelloWorld->ButtonsList->ButtonsPlus,ButtonsMinus Below is their code

<script setup lang="ts">
import { ref } from 'vue'
import ButtonsList from './ButtonsList/ButtonsList.vue'
defineProps<{ msg: string }>()
const plusHandler = () => {
  count.value = count.value + 1
}
const minusHandler = () => {
  count.value = count.value - 1
}
const count = ref(0)
</script>

<template>
  <h1>{{ msg }}</h1>

  <div class="card">
    <p>count is {{ count }}</p>

  </div>

  
  <ButtonsList @update:plusEmit="plusHandler"  @update:minusEmit="minusHandler"  />
</template>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>





<script setup>
import ButtonPlus from '../Buttons/ButtonPlus.vue'
import ButtonMinus from '../Buttons/ButtonMinus.vue'
</script>



<template>
  <ButtonPlus/>
  <ButtonMinus/>    
</template>





<script setup>
    const emit = defineEmits();
    const plus = () => {
        emit('update:plusEmit')
    }
</script>


<template>
    <button @click="plus" >
        +
    </button>
</template>





<script setup>
    const emit = defineEmits();
    const minus = () => {
        emit('update:minusEmit')
    }
</script>


<template>
    <button @click="minus" >
        -
    </button>
</template>

Why, if I have one button in the ButtonsList component, then everything works correctly, and if there are two, then nothing works at all, and how should this functionality be implemented (if you do not use function passing to change as in React)? i'm using vue3

I tried use different variables of using emits but nothing work


Solution

  • You're attaching the listeners to the update:plusEmit and update:minusEmit on the ButtonsList component. The problem is that component doesn't emit those events. Event listeners have to be placed on the components that emit those events, in your case, they won't bubble up to the parent.

    You could either:

    1. Define the same events on the ButtonList component and emit them when the child emits their event like this:
    <ButtonPlus @update:plusEmit="emit('update:plusEmits')" />
    <ButtonMinus @update:minusEmit="emit('update:minusEmits')"/>   
    
    1. Or do away with the subcomponents for the buttons and define them in the ButtonsList