Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

vue.js - Delete a Vue child component

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...