gpt4 book ai didi

vue.js - 如何从 Vue 组件中的表中删除行?

转载 作者:行者123 更新时间:2023-12-05 05:19:43 25 4
gpt4 key购买 nike

我是 Vue 的新手,一整天都在为此苦苦挣扎。我正在尝试使用允许用户添加和删除行的 Vue 组件构建一个表。

我遇到的问题是 removeRow() 函数没有删除选定的行,而是删除了表格的最后一行。谁能帮帮我?

Vue.component('newtemplate', {
template: `<div>
<div>
<button class="button btn-xs btn-success" @click="addRow">+</button>
</div>
<table>
<thead>
<tr>
<th class="col-lg-6 nopadding"><input type="text" value="Col 1" class="borderless nopadding col-lg-6"></th>
<th class="col-lg-2 nopadding"><input type="text" value="Col 2" class="borderless nopadding col-lg-12"></th>
<th class="col-lg-2 nopadding"><input type="text" value="Col 3" class="borderless nopadding col-lg-12"></th>
<th class="col-lg-2 nopadding"><input type="text" value="Col 4" class="borderless nopadding col-lg-12"></th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in rows" :row="row">
<td>
<input type="text" class="form-control nopadding text-center">
</td>
<td>
<input type="text" class="form-control nopadding text-center">
</td>
<td>
<input type="text" class="form-control nopadding text-center">
</td>
<td>
<input type="text" class="form-control nopadding text-center">
</td>
<td>
<button type="button" class="text-center button btn-xs btn-danger" v-on:click="removeRow(index)">-</button>
</td>
</tr>
</tbody>
</table>
</div>`,
data: function() {
return {
rows: [{row: ""}]
}
},
methods:{
addRow(){
this.rows.push({row: ''});
},
removeRow: function(index) {
this.rows.splice(index, 1);
}
}
});

更新我做了一个 fiddle https://jsfiddle.net/4d2uzx0r/

最佳答案

Vue 正在从 rows 中删除适当的项目,但您没有将输入绑定(bind)到任何内容,因此 Vue 不知道表行输入中的值,它只知道它需要渲染更少的行。 Vue 在可以并且只能跟踪它知道的状态时采取捷径。

我已经 updated your fiddle将第一列绑定(bind)到行元素(每个行项现在是一个数组)。如果您在第一列中填写值,您会看到它删除了相应的行。

<input type="text" class="form-control nopadding text-center" v-model="row[0]">

addRow() {
this.rows.push({
row: []
});
},
removeRow: function(index) {
console.log("Removing", index);
this.rows.splice(index, 1);
}

关于vue.js - 如何从 Vue 组件中的表中删除行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45612122/

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