Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a Vue child component

Tags:

vue.js

I'm really stuck on this one.I have created a Vue (2.0) component that is made up of child components, it's all being Webpacked etc. For example, this is the parent:

<div>

    <h1>This is just a title for lulz</h1>

    <rowcomponent v-for="row in rows" :row-data="row"></rowcomponent>

</div>

which has a prop of rows passed to it which looks something like this:

rows: [{ sometext: "Foo"} , { sometext: "Bar" }]

So my row component looks like this:

<div>{{ this.sometext }} <button @click="deleteRow">Delete Row</button></div>

And I feel like it should be really easy to set a method on the rowcomponent that is something like this:

deleteRow() {
    this.delete();
}

Do I need to $emit something to the parent with the index of the row in it to remove it? It's driving me crazy. All the examples seem to suggest it would be easy to do, but not in the case where you have child components that want to delete themselves.

like image 666
Ben Harvey Avatar asked Oct 21 '16 16:10

Ben Harvey


1 Answers

Yes, the child component cannot delete itself. The reason is because the original data for rows is held in the parent component.

If the child component is allowed to delete itself, then there will be a mismatch between rows data on parent and the DOM view that got rendered.

Here is a simple jsFiddle for reference: https://jsfiddle.net/mani04/4kyzkgLu/

As you can see, there is a parent component that holds the data array, and child component that sends events via $emit to delete itself. The parent listens for delete event using v-on as follows:

<row-component
    v-for="(row, index) in rows"
    :row-data="row"
    v-on:delete-row="deleteThisRow(index)">
</row-component>

The index property provided by v-for can be used to call the deleteThisRow method, when the delete-row event is received from the child component.

like image 104
Mani Avatar answered Nov 04 '22 23:11

Mani