Home > Back-end >  vuejs 3: declare an emit event in a child component via emits option
vuejs 3: declare an emit event in a child component via emits option

Time:06-06

Using Vue 3.2 and I'm under the impression that I follow the documentation

I'm sending an array of objects to a child component and in return, I am trying to emit an event to the parent compenent so one object (identified by id) gets deleted from the array.

// parent
<template>
    <TheAccountLines :lines=recurrents_credits @goaway(id)="goaway(id)" />
</template>

<script setup>
import { find } from "lodash"
// this doesn't get called at all, just putting it here to show that the function exists.
const goaway = (id) => {
  var line = find (state.accounts, {id:id})
  console.log(line)
}
</script>
// child component
<template>
 <div v-for="line in lines" :key="line.id">
    <span @click="goaway(line.id)" >X</span>
    {{ line.foo) }}
    {{ line.bar}}
  </div>
</template>
<script setup>
const props = defineProps({ 'lines': Array)}
const emit = defineEmits(['goaway'])
const goaway = (id) => emit('goaway', id)

</script>

Upon page load, I get this message in the console: Extraneous non-emits event listeners (goaway(id)) were passed to component but could not be automatically inherited because component renders fragment or text root nodes. If the listener is intended to be a component custom event listener only, declare it using the "emits" option.

I understand the "emits" option to be defineProps. But I must be wrong.

CodePudding user response:

I think the problem is: you should use @goaway, but not @goaway(id).

Part of template:

<template>
<!--- THIS IS WRONG, SEE UPDATE BELOW -->
  <TheAccountLines :lines="recurrents_credits" @goaway(id)="goaway(id)" />
</template>

BTW, you can use onGoaway prop instand @goaway:

// parent component
<template>
  <TheAccountLines :lines="recurrents_credits" @goaway="goaway" />
</template>

// child component
<script setup>
const props = defineProps(['onGoaway'])

const emitDelete = (id) => { props.goaway(id) }
</script>

CodePudding user response:

Like always, after hours of searching, I find the answer 5 minutes after asking the question here. I will not delete the question (unless moderation prefers I do that).

The error was in the parent : don't use the parameters in the emit :

documentation

<TheAccountLines :lines=recurrents_credits @goaway="goaway" />
  • Related