javascript - 如何在Vue中为多个选定项目的背景着色?
问题描述
我在下面有用于类别选择的代码。选择类别时,它将其背景设置为绿色,否则背景为灰色;这很好用。
我想要实现的是当我选择多个项目时,我希望它为所有选定的类别保持背景绿色。有没有办法做到这一点?
<div class="categories" v-for="(category, index) in categories" :key="index" @click="Add( category._id, index)" :class="[isediting && selectedIndex == index ? 'green' : 'gray']">
{{ category.category_name }}
</div>
<script>
methods: {
Add(AddCategory, index) {
this.AddCategory.push(AddCategory);
this.selectedIndex = index;
this.isediting = true;
},
</script>
<style>
.green {
background-color: #41B883;
}
.gray {
background-color: #e5e0ed;
}
</style>
解决方案
为了适应这种情况,唯一需要进行的主要更改是创建selectedIndex
一个数组而不是单个值,以便我们可以保存多个选择。
例如。:
- 设置为
selectedIndex
数组[]
data()
- 单击时,我们应该将值推送到数组而不是设置为相等
- 要检查是否选择了给定索引,我们使用
selectedIndex.includes(index)
而不是selectedIndex == index
但是,允许多项选择还有另一个副作用,即增加了对单击取消选择的支持。但这也很简单,我们只需要检查是否selectedIndex
已经包含 中的值Add()
,如果包含,则将其删除。我们可以用它Array.prototype.splice()
来做到这一点。
这是一个交互式版本:
new Vue({
el: '#app',
data() {
return {
selectedIndex: [],
categories: [{ _id: 0, category_name: 'noodles' }, { _id: 1, category_name: 'pizza' }, { _id: 2, category_name: 'hamburgers' } ],
}
},
methods: {
Add(AddCategory, index) {
//Check if item is selected...
if (this.selectedIndex.includes(index))
this.Remove(index); //If so, remove from selectedIndex
else
this.selectedIndex.push(index); //If not, add to selectedIndex
},
Remove(index) { //Find index in selectedIndex, and splice out
this.selectedIndex.splice(this.selectedIndex.indexOf(index),1);
},
RemoveAll() { //To deselect all, we empty the selectedIndex array
this.selectedIndex = [];
},
}
});
.green {
background-color: #41B883;
}
.gray {
background-color: #e5e0ed;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
<div v-for="(category, index) in categories"
@click="Add( category._id, index)"
:class="[selectedIndex.includes(index) ? 'green' : 'gray']"
>
{{ category.category_name }}
</div>
<br>
<button @click="RemoveAll">Unselect All</button>
</div>
推荐阅读
- reactjs - 我应该在哪里更新过滤的数据,在 saga、reselect 或 reducer 中?
- php - 在 PHP 联系表单中重定向
- flutter - 如何在颤动中对json数据进行排序?
- flutter - 一页中有两个 Bloc Builders(屏幕)
- json - 如何正确将案例类中的 None 字段转换为 JSON
- java - 为什么我的 Java 猜谜游戏在第一个循环后不起作用
- python - Docker撰写安装卷不起作用
- c# - 运行本地 Web 应用程序但限制对资源的访问
- c# - 将矩形形式的winform剪裁为图像
- postman - 使用邮递员在 pinterest 上的板上添加图钉