gpt4 book ai didi

javascript - 如何使用 v-for 删除行

转载 作者:行者123 更新时间:2023-12-02 16:02:22 24 4
gpt4 key购买 nike

为此我正在填充一个推送并为每一行添加一个索引,我需要的是删除该行。

addTrabajo(state) {
state.trabajos.push({
vehicle_id: state.newOrdenTrabajo.vehicle_id,
km: state.newOrdenTrabajo.km,
descripcion: state.newOrdenTrabajo.descripcion,
})
},

enter image description here

OrdenTrabajo.vue

 <table class="table table-hover table-striped mt-3 table-sm text-white bg-dark">
<thead>
<tr>
<th>#</th>
<th>Trabajo</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="(trabajo, index) in trabajos" :key="index">
<td>{{index + 1}}</td>
<td>{{ trabajo.descripcion }}</td>
<td>
<a
href="#"
class="btn btn-danger btn-sm"
@click.prevent="removeFromTrabajo({ id: index + 1 })"
data-toggle="tooltip"
data-placement="top"
title="Eliminar">
<i class="fas fa-ban"></i>
</a>
</td>
</tr>
</tbody>
</table>

script.js

removeFromTrabajo(state, data) {
let found = state.trabajos.indexOf(data.id)
state.trabajos.splice(found)
},

问题是在淘汰的时候,最后一个不是被选中的也被淘汰了。例如:我选择了第一个,但是最后一个正在被删除。

最佳答案

您只需要将index 传递给函数即可。在 removeFromTrabajo 中,您可以使用 this.trabajos 直接访问列表,检查它处的项目是否存在,然后使用 Array#splice通过传递第二个参数删除此索引处的项目:

deleteCount (Optional):: An integer indicating the number of elements in the array to remove from start. If deleteCount is omitted, or if its value is equal to or larger than array.length - start (that is, if it is equal to or greater than the number of elements left in the array, starting at start), then all the elements from start to the end of the array will be deleted. If deleteCount is 0 or negative, no elements are removed.

new Vue({
el: "#table",
data: () => ({
trabajos: [ { descripcion: '1' }, { descripcion: '2' }, { descripcion: '3' } ]
}),
methods: {
removeFromTrabajo(index) {
const item = this.trabajos[index];
if(item) {
this.trabajos.splice(index, 1);
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://kit.fontawesome.com/a076d05399.js"></script>

<table id="table" class="table table-hover table-striped mt-3 table-sm text-white bg-dark">
<thead>
<tr><th>#</th> <th>Trabajo</th><th></th></tr>
</thead>
<tbody>
<tr v-for="(trabajo, index) in trabajos" :key="index">
<td>{{index + 1}}</td>
<td>{{ trabajo.descripcion }}</td>
<td>
<a
href="#"
class="btn btn-danger btn-sm"
@click.prevent="removeFromTrabajo(index)"
data-toggle="tooltip"
data-placement="top"
title="Eliminar">
<i class="fas fa-ban"></i>
</a>
</td>
</tr>
</tbody>
</table>

关于javascript - 如何使用 v-for 删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70321656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com