0

I have a Parent.vue, where i send an object to a Child component, and get back the updated item every now and then via this.$emit('updateItem', item).

<template>
  <div>
    <Child
      v-for="(item, index) in items"
      :key="index"
      :item="item"
      @updateItem="updateItem"
      // @updateItem="updateItem(index, dataFromChildComponent)" // this is what i would like to do
    />
  </div>
</template>

<script>
export default {
  name: 'Parent',

  data() {
    return {
      items: [] // List of objects
    }
  },

  methods: {
    updateItem (index, data) {
      // Receive the data and the index
    }
  }
}
</script>

The problem i keep running into is how to locate the object in the list of items in the Parent to update the correct one. I would like to enrich this data to add e.g. an index to be able to locate the item in the list. Is there any way to achieve this or is it actually the correct way to propagate the index down to the Child in order to emit it back up again? Feels like an anti-pattern to me.

2 Answers 2

2

You have several options to achieve that:

  1. You can pass as a props index to child component and then in child emit function send object containing updated index with updated value.
  2. You can change your current code to something like this: @updateItem="updateItem(index, $event)" where $event is updated value
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. I did not know, i still have access to $event in the Parent
1

Updating your event listener as @updateItem="data => updateItem(index, data)" should work. Assuming you have emitted data from child component (i.e. something like this.$emit('updateItem', somedata)).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.