Removing a Vue Child Component

I am really stuck with this. I created the Vue (2.0) component, which consists of child components, all of this is Webpacked, etc. For example, this is the parent element:

<div> <h1>This is just a title for lulz</h1> <rowcomponent v-for="row in rows" :row-data="row"></rowcomponent> </div> 

which has a rows registration that looks something like this:

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

So my string component is as follows:

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

And I feel that it is very simple to set the method on rowcomponent , something like this:

 deleteRow() { this.delete(); } 

Do I need $ emit something parent with the row index in it to remove it? It drives me crazy. All the examples seem to suggest that this will be easy to do, but not if you have child components that want to remove themselves.

+6
source share
1 answer

Yes, a child component cannot remove itself. The reason is that the raw data for rows stored in the parent component.

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

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

As you can see, there is a parent component that contains an array of data, and a child component that dispatches events via $emit to remove itself. The parent listens for the 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 a child component.

+15
source

Source: https://habr.com/ru/post/1011559/


All Articles