Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JarekTkaczyk's avatar

how to remove component from parent's array

Like in the title and this pseudo code: https://gist.github.com/jarektkaczyk/d0f89852205ec1ab69cb

0 likes
5 replies
JarekTkaczyk's avatar

@premsaurav Maybe I wasn't clear enough in that gist, since it was cut for brevity :)

Assuming we have simple data:

new Vue({
  el : 'body',
  data : {
    items [ {id:1, name: name_1}, {id: 2, name: name_2}, ...]
  }
})

then we can easilly do:

<div v-for="item in items">
  {{ item.name }}
  <button @click="items.$remove(item)">remove</button>
</div>

BUT when you have a component instead:

<some-component v-for="item in items"></some-component>

then this won't work:

Vue.component({
  template:
`<div>
  {{ name }}
  <button @click="$parent.items.$remove(this)">remove</button>
</div>`
})

because this != item in the parent's array (it refers to whole component, not just raw data). Obviously it could be easy for static items, because we can just filter by the id, but my question is about dynamically added elements, and those don't have an id yet...

BTW I use events dispatching for this, so the action is handled by the appropriate method in the parent scope, but it doesn't matter here.

jimmck's avatar

My only change to @thomaskim is I keep the data in the component. Then use methods to operate on it. Then the component only cares about its own state. The parent manages the component.

1 like
cipsas's avatar

you can pass via props whole item object. then

<button @click="$parent.items.$remove(item)">remove</button>
1 like

Please or to participate in this conversation.