[英]splice() wrong component in data array
Let's say I have a form, and can add or remove a column by a click.假设我有一个表单,可以通过单击添加或删除一列。
I use v-for
to render the vue components, when I try to use splice()
to delete a specific component, it always delete the last component in the array.我使用
v-for
渲染 vue 组件,当我尝试使用splice()
删除特定组件时,它总是删除数组中的最后一个组件。
I can't figure out what I did wrong here, any hint will be very appreciated.我无法弄清楚我在这里做错了什么,任何提示将不胜感激。
Here is a part of my code: the problem is occured at removePerson
method.这是我的代码的一部分:问题出现在
removePerson
方法中。
Parent Component父组件
<template>
<div class="form-container">
<template>
<div v-for="(child, key) in otherPersonArray" :key="key" class="form-container">
<button @click="removePerson(key)" class="close">X</button>
<component :is="child"></component>
</div>
</template>
<button @click="addPerson" >+ Add Person</button>
</div>
</template>
<script>
import otherPerson from './OtherPerson';
export default {
components: {
otherPerson
},
data() {
return {
otherPersonArray: [],
}
},
methods: {
addPerson() {
if (this.otherPersonArray.length <= 10) {
this.otherPersonArray.push(otherPerson);
}
},
removePerson(key) {
this.otherPersonArray.splice(key, 1);
},
},
}
</script>
For example, when I try to delete the component which input value is 1, it delete the component which input value is 2.例如,当我尝试删除输入值为 1 的组件时,它会删除输入值为 2 的组件。
otherPerson component otherPerson组件
<template>
<div class="form-container">
<div class="person">
<div class="row">
<div class="form-group col-6">
<label for="inventor-last-name">Lastname of Person *</label>
<div class="input-container">
<input v-model="lastName" type="text" class="form-control form-control-lg">
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
lastName: '',
}
},
}
</script>
there are couple of ways to achieve this but for now can you try these:有几种方法可以实现这一点,但现在你可以试试这些:
removePerson(key) {
this.otherPersonArray = this.otherPersonArray.filter(person => {
return person.key === key;
})
}
OR或者
const index = this.otherPersonArray.indexOf(ele by key); // get index by key person key
if (index > -1) {
this.otherPersonArray.splice(index, 1);
}
What I am understanding key is index here then you should follow this:我理解的关键是这里的索引,那么你应该遵循这个:
var filtered = this.otherPersonArray.filter(function(value, index){
return index !== key;
});
let me know if still it not working for you?让我知道它是否仍然不适合您?
Here is example:这是示例:
You can use Array.prototype.filter
您可以使用
Array.prototype.filter
removePerson(key) {
this.otherPerson = this.otherPersonArray.filter((x, i) => i !== key);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.