删除一个 Vue 子组件 [英] Delete a Vue child component

查看:50
本文介绍了删除一个 Vue 子组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很坚持这个.我创建了一个由子组件组成的 Vue (2.0) 组件,它都是 Webpacked 等.例如,这是父组件:

<h1>这只是 lulz 的标题</h1><rowcomponent v-for="row in rows" :row-data="row"></rowcomponent>

它有一个 rows 的 prop 传递给它,看起来像这样:

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

所以我的行组件看起来像这样:

<div>{{ this.sometext }} 

而且我觉得在 rowcomponent 上设置一个方法应该很容易,就像这样:

deleteRow() {this.delete();}

我是否需要向父项 $emit 中包含行索引的内容以将其删除?这让我疯狂.所有的例子似乎都表明这很容易做到,但在您有想要删除自己的子组件的情况下则不然.

解决方案

是的,子组件不能删除自己.原因是rows的原始数据保存在父组件中.

如果允许子组件删除自身,那么父组件上的rows数据和渲染的DOM视图之间将不匹配.

这里有一个简单的jsFiddle供参考:https://jsfiddle.net/mani04/4kyzkgLu/

如你所见,有一个父组件保存数据数组,子组件通过$emit发送事件删除自身.父级使用 v-on 监听删除事件,如下所示:

</row-component>

v-for 提供的index 属性可用于调用deleteThisRow 方法,当delete-row 事件是从子组件接收的.

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.

解决方案

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.

这篇关于删除一个 Vue 子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆