首页 > 解决方案 > 如何在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>

标签: javascriptcssvue.js

解决方案


为了适应这种情况,唯一需要进行的主要更改是创建selectedIndex一个数组而不是单个值,以便我们可以保存多个选择。

例如。:

  1. 设置为selectedIndex数组[]data()
  2. 单击时,我们应该将值推送到数组而不是设置为相等
  3. 要检查是否选择了给定索引,我们使用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>


推荐阅读