首页 > 解决方案 > Vue js:函数删除在我的代码中无法正常工作

问题描述

我在 Vue js 中有下面的代码,它显示来自 API 的类别,每当我单击其中任何一个时,它都会将其添加到数组 AddCategory 并将其发布到 API,我还实现了按钮 Removeall,每当我单击它时,它都会删除所有数组中的选定类别(它将清空数组)并且工作正常。我的问题是,当我想再次单击选定的单个类别(在下面的函数删除中)时,它没有从数组中弹出它,而是将它推了两次,有什么帮助吗?

<template>
  <b-row class="categories-row">
            <div
              class="categories"
              v-for="(category, index) in categories"
              :key="index"
              @click="Add(category._id, index)"
              :class="[selectedIndex.includes(index) ? 'green' : 'gray']"
              required
            >
              {{ category.category_name }}
            </div>
          </b-row>

</template>


export default {
  
  data() {
    return {
      categories: [],
      selectedIndex: [],
      AddCategory: [],
     

      posts: {
        description: null,
        questionTitle: null,
        categories: null,
        
      },
    };
  },
  methods: {
    Add(AddCategory, index) {
         
  if (this.selectedIndex.includes(index)) 
        this.Remove(index); 
      else
      this.selectedIndex.push(index);
      this.AddCategory.push(AddCategory);
    },
      Remove(index) { //not working
      this.selectedIndex.splice(this.selectedIndex.indexOf(index),1);
    },


    RemoveAll() {
      this.AddCategory = [];
      this.selectedIndex.splice(this.AddCategory);
    },}}

标签: javascriptvue.js

解决方案


尝试这个:

Remove(index) { 
      this.selectedIndex = this.selectedIndex.filter((item)=> item !== index) ;      
}

编辑:

@sara97 也许您也需要从 this.AddCategory 中删除它。

编辑:

@sara97 并且因为它运行“this.AddCategory.push(AddCategory);” 每次。在 if 和 else 中使用 {}。

  Add(AddCategory, index) {
   if (this.selectedIndex.includes(index)) {
        this.Remove(AddCategory,index); 
      }else{
      this.selectedIndex.push(index);
      this.AddCategory.push(AddCategory);}
    },

  Remove(AddCategory,index) { 
      this.selectedIndex = this.selectedIndex.filter((item)=> item !== index);
      this.AddCategory = this.AddCategory.filter((item)=> item !== AddCategory)
    },

推荐阅读