javascript - 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);
},}}
解决方案
尝试这个:
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)
},
推荐阅读
- python - python re正则表达式冻结对随机文本的处理
- visual-studio-code - 如何设置 CodeLLDB 以调试从 Java 进程调用的 Rust 可执行文件?
- excel - 下载保存在烧瓶服务器上的 excel 文件
- tsql - T-SQL 使用 Lead () 函数,但不允许在 GROUP BY 或 UPDATE 中使用
- html - 为什么我的 CSS 动画在除 Safari 之外的所有浏览器中都有效?
- javascript - 比较两个对象数组并在 Javascript 中值为 true 时返回一个新数组
- oracle-sqldeveloper - 如何在sql中根据月份将值的数量分组到列中
- javascript - 在没有本地存储的情况下在本地存储信息的最佳方式是什么?
- python - 断言“GDK_IS_DISPLAY(显示)”失败 - 无法确定以下参数的类型:数据
- reactjs - 如何访问 gatsby-theme-material-ui-top-layout 中的 {window, location}