Vue JS中如何根据数组动态添加/删除插槽字段
P粉639667504
P粉639667504 2023-08-28 17:43:21
[Vue.js讨论组]
<p>我有以下代码,它接受一个包含要重复的HTML字段的插槽:</p> <pre class="brush:php;toolbar:false;">&lt;div v-for=&quot;(row, index) in rows&quot; :key=&quot;index&quot;&gt; &lt;div class=&quot;d-flex justify-content-between &quot;&gt; &lt;slot name=&quot;fields&quot;&gt; &lt;/slot&gt; &lt;input v-model=&quot;row.value&quot; /&gt; &lt;button @click=&quot;removeRow(index)&quot; type=&quot;button&quot; class=&quot;btn btn-primary waves-effect waves-float waves-light height-10-per &quot; &gt; Remove &lt;i class=&quot;fa fa-times-circle&quot;&gt;&lt;/i&gt; &lt;/button&gt; &lt;/div&gt; &lt;/div&gt;</pre> <p>当我使用<code>removeRow(index)</code>时,它总是移除最后一个插槽。我已经测试了使用<code>&lt;input v-model=&quot;row.value&quot;&gt;</code>,正确的输入在这里被移除了,但从未移除正确的插槽。</p> <p>我不需要插槽中的输入是动态的或与Vue交互,我只是想允许用户通过Vue组件动态添加/删除行。</p> <p>请查看我用于添加/删除行的下面两种方法,以防问题出在这里:</p> <pre class="brush:php;toolbar:false;">removeRow(index){ this.rows.splice(index, 1); }, addRow(){ this.rows.push({value: 'test'}) }</pre> <p>非常感谢任何帮助。</p>
P粉639667504
P粉639667504

全部回复(1)
P粉463824410

为您的 v-for 循环元素添加一个独特的 key 值:

<div-for="(row, index) in rows" :key="JSON.stringify(row)">

这样可以确保从 DOM 中正确地移除元素。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号