简体   繁体   中英

How to filter an Array with Checkboxes items?

I want to filter my checkboxes I search it on internet there was information but I couldn't work it with my code.

This is the webpage在此处输入图像描述

I want when you click on the checkbox it must be same as the category.

This is some code of the checkbox:

<div>
  <input class="form-check-input checkboxMargin" type="checkbox" value="All" v-model="selectedCategory">
  <p class="form-check-label checkboxMargin">All</p>
</div>

This is my grey box layout:

<div class="col-sm-12 col-md-7">
        <div class="card rounded-circle mt-5" v-for="item of items" :key="item['.key']">
          <div>
            <div class="card-body defaultGrey">
              <h5 class="card-title font-weight-bold">{{ item.name }}</h5>
              <div class="row mb-2">
                <div class="col-sm ">
                  <div class="row ml-0"><h6 class="font-weight-bold">Job:</h6><h6 class="ml-1">{{ item.job }}</h6></div>
                  <div class="row ml-0"><h6 class="font-weight-bold">Category:</h6><h6 class="ml-1">{{ item.categories }}</h6></div>
                  <div class="row ml-0"><h6 class="font-weight-bold">Location:</h6><h6 class="ml-1">{{ item.location }}</h6></div>
                  <div class="row ml-0"><h6 class="font-weight-bold">Niveau:</h6><h6 class="ml-1">{{ item.niveau }}</h6></div>
                  <div class="row ml-0"><h6 class="font-weight-bold">Availability:</h6><h6 class="ml-1">{{ item.availability }}</h6></div>
                  <h6>{{ item.info }}</h6>
                  <div class="row ml-0"><h6 class="font-weight-bold">Posted:</h6><h6 class="ml-1">{{ item.user }}</h6></div>
                </div>
              </div>
              <div class="row">
                <div class="col-xs-1 ml-3" v-if="isLoggedIn">
                  <router-link :to="{ name: 'InternshipDetails', params: {id: item['.key']} }" class="btn bg-info editbtn">
                    Details
                  </router-link>
                </div>

                <div class="col-xs-1 ml-3 mr-3" v-if="isLoggedIn && item.user == currentUser">
                  <router-link :to="{ name: 'Edit', params: {id: item['.key']} }" class="btn btn-warning editbtn">
                    Edit
                  </router-link>
                </div>

                <div class="col-xs-1" v-if="isLoggedIn && item.user == currentUser">
                  <button @click="deleteItem(item['.key'])" class="btn btn-danger dltbtn">Delete</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

And I have my object here but how can I filter my grey boxes with category:

selectedCategory: []

You need to create one-way binding between your CategoryCheckBox component and your ListCard component.

Because you provided separated code when I can not reproduce it to give you a solution based on your own, I suggest this example to explain my solution.

Step One:

You have many ways to CRUD your items using a Plugins or Vuex or global instance , in my example I used global instance in main.js

Vue.prototype.$myArray = ["Books", "Magazines", "Newspaper"];

I assume you created your items data in the ListCards component

Step Two:

You need to add @change event in your checkbox to handle checked and unchecked states. I used static data (Book) for value .

 <label>
<input type="checkbox" value="Books" @change="handleCategory($event)" /> Books

Now, let's implement handleCategory method, but before that, as we know that Checkbox and ListCards are independents which means we need to define a bus to create event communication between them and this is your issue so we define the bus inside the main.js

Vue.prototype.$bus = new Vue({});

Now we define handleCategory like this:

methods: {
    handleCategory(e) {
      this.$bus.$emit("checkCategory", e);
    }
  }

Step Three:

How can our ListCards listen to this event ?

By call $bus.$on(..) when the component is created ( Hope you know what Vue lifecycle methods mean )

created() {
    this.$bus.$on("checkCategory", e => this.checkCategory(e));
  },

When the user click the check box the component runs handleCategory then runs checkCategory inside ListCard .

Inside my ListCard, I have categories and originalCategories as data

 data() {
    return {
      categories: this.$myArray,
      originalCategories: this.$myArray
    };
  },

and a template:

<ul v-for="(category,index) in categories" :key="index">
      <CategoryItem :categoryName="category" />
    </ul>

and a created method ( lifecycle )

 created() {
    // $bus is a global object to communicate between components
    this.$bus.$on("checkCategory", e => this.checkCategory(e));
  },

and our filtering methods:

 methods: {
    checkCategory(e) {
      let target = e.target;
      let value = e.target.value;

      target.checked
        ? this.filterCatergories(value)
        : (this.categories = this.originalCategories);
    },
    filterCatergories(value) {
      this.categories = this.categories.filter(val => val === value);
    }
  }

What's important for you is:

this.categories.filter(val => val === value); //will not do nothing
const categories=this.categories.filter(val => val === value); //will update the view.

And you can change the code or make it better and simple.

@Update

You can also use computed properties but because we have a parameter here which is the category name we need get and set .

  computed: {
    filteredItems: {
      get: function() {
        if (this.selectedCategory.length == 0) return this.items;
        return this.items.filter(value => {
          for (const category of this.selectedCategory) {
            if (value == category) return value;
          }
        });
      },
      set: function(category) {
        this.selectedCategory.push(category);
      }
    }
  },
  methods: {
    checkCategory(e) {
      let target = e.target;
      let value = e.target.value;

      target.checked
        ? (this.filteredItems = value)
        : this.selectedCategory.pop(value);
    }
  }

Use computed properties:

computed: {
   filteredItems(){
      if(this.selectedCategory.length == 0) return this.items;
      return this.items.filter(el => {
         for(let i = 0; i < this.selectedCategory.length; i++){
            if(el.categories == this.selectedCategory[i]) return el;
         }
      });

   }
}

Then you go for v-for="item of filteredItems"

I didnt tested it. If you provide me more code i could help you more

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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