我是 VueJS 的新手,现在我遇到了一个我无法弄清楚的问题。我想通过单击按钮动态添加和删除元素。我如何让它工作,所以我可以删除一个特定的 div 而不是总是我添加的最后一个。我玩了很多,现在我什至收到错误 [Vue warn]: You may have an infinite update loop in a component render function。我可能不应该设置 div=index 而是使用 div.id 等。希望有人能帮我解决这个问题。谢谢。
https://jsbin.com/zuquwej/edit?html,js,output
<div id="app">
<div
v-for="(div, index) in divs"
:key="div.id"
:div="div=index"
>
<div class="row">
<div class="col-12">Div {{div}}</div>
</div>
<button
class="btn btn-danger"
@click="deleteRow(index)"
>Delete</button>
</div>
<button
class="btn btn-success"
@click="addRow"
>Add row</button>
</div>
const app = new Vue({
el: '#app',
data() {
return {
div: 0,
divs: []
};
},
methods: {
addRow() {
this.divs.push({
div: this.div
});
console.log(this.divs);
},
deleteRow(index) {
this.divs.splice(index, 1);
}
}
})
最佳答案
您应该为您生成的每个对象存储一个索引,并将其存储到组件的 divs
属性中。顺便说一句,与数组索引不同,如果你从这个数组中拼接一个元素,它不会改变。这是一个工作示例:
<div
v-for="div in divs"
:key="div.id"
>
<div class="row">
<div class="col-12">Div {{ div.name }}</div>
</div>
<button
class="btn btn-danger"
@click="deleteRow(div.id)"
>Delete</button>
</div>
const app = new Vue({
el: '#app',
data() {
return {
index: 0,
divs: []
};
},
methods: {
addRow() {
this.divs.push({
id: this.index,
name: 'div' + this.index,
});
this.index++;
},
deleteRow(index) {
this.divs.splice(index, 1);
}
}
})
关于vue.js - 在 Vue JS 组件中动态添加和删除 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61145426/