简体   繁体   English

如何删除(删除)对象数组中的特定项目

[英]how to delete(remove) a particular item in an array of objects

I want to use a delete function to remove a specific object in an array. 我想使用删除功能删除数组中的特定对象。

I tried the splice() method but it removes just the first array no matter which objects I clicked on 我尝试了splice()方法,但是无论我单击哪个对象,它都只会删除第一个数组

Here is the code for object with a v-for method 这是使用v-for方法的对象的代码

 <li v-for=" skill in skills" :key="skill.id">
        {{skill.skill}}
        <i class="fa fa-minus-circle v-on:click="remove(skill)"></i>
      </li>

here is the Skill.vue 这是Skill.vue

 <script>
import uuid from "uuid";
export default {
  name: "Skills",
  data() {
   return {
  skill: "",
  skills: [
    { id: uuid.v4(), skill: "Vue.js" },
    {
      id: uuid.v4(),
      skill: "Javascript"
    },
    {
      id: uuid.v4(),
      skill: "Rails"
    }
  ]
 };
},
methods: {
addSkill() {
  this.$validator.validateAll().then(result => {
    if (result) {
      this.skills.push({ skill: this.skill, id: uuid.v4() });
      this.skill = "";
    }
  });
},
remove(id) {
  this.skills.splice(id, 1);
 }
}

}; };

How can I construct the method 我该如何构造方法

remove(id) {
  this.skills.splice(id, 1);
 }

to delete the specific object? 删除特定对象?

To use splice() you should be passing the index of the item as parameter. 要使用splice()您应该将该项的索引作为参数传递。 To remove an item based on a property, consider using filter() instead. 要删除基于属性的项目,请考虑改用filter()

Template should be: 模板应为:

<li v-for="skills in skill" :key="skill.id">
  {{skill.skill}}
  <i class="fa fa-minus-circle v-on:click="remove(skill.id)"></i>
</li>

And the method: 和方法:

remove(id) {
  this.skills = this.skills.filter(skill => skill.id !== id);
}

It will return a copy of the array without the items where skill.id !== id evaluates to false . 它将返回数组的副本,其中不包含skill.id !== id评估为false

you should pass the index : 您应该通过索引:

array.splice( index , howmany, item1, ....., itemX) array.splice( index ,howmany,item1,.....,itemX)

splice 拼接

<li v-for=" (skills,index) in skill" :key="skill.id">
        {{skill.skill}}
        <i class="fa fa-minus-circle v-on:click="remove(index)"></i>
      </li>

so : 所以:

remove(index) {
  this.skills.splice(index, 1);
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM