Alix
Alix

Reputation: 23

Combined checkbox filters on Vue.js

I'm working on my first Vue.js project that contain JSON data, that should be filtered by several properties. I need to make checkbox filter on Vue.js. I have two of them. Separately they work, but when I try to combine them, they don't. Here is my code:

<template>
  <div id="app1">
    <div v-for="userId in userIds" class="check-userid">
      <input type="checkbox" v-model="checkedUserIds" v-bind:value="userId">
      {{userId}}
    </div>
    <br>

    <div v-for="id in ids" class="check-id">
      <input type="checkbox" v-model="checkedIds" v-bind:value="id">
      {{id}}
    </div>

    <br>

    <div v-for="job in filteredJobs1">
      <h2>{{ job.id }}) {{ job.title }}</h2>
      <div>{{ job.body }}</div>
    </div>

    <div v-for="job in filteredJobs2">
      <h2>{{ job.id }}) {{ job.title }}</h2>
      <div>{{ job.body }}</div>
    </div>

  </div>
</template>
import axios from "axios";

export default {
  name: "Checkbox",
  data() {
    return {
      jobs: [],
      userIds: [1, 2, 3],
      ids: [1, 2, 3, 4, 5, 6, 7, 8,9, 10],
      checkedUserIds: [],
      checkedIds: []
    };
  },
  created() {
    axios
      .get("https://jsonplaceholder.typicode.com/posts")
      .then(response => (this.jobs = response.data));
  },
  computed: {

    filteredJobs1() {
      if (!this.checkedUserIds.length) return this.jobs;
      return this.jobs.filter(job => this.checkedUserIds.includes(job.userId));      
    },

    filteredJobs2() {
      if (!this.checkedIds.length) return this.jobs;
      return this.jobs.filter(job => this.checkedIds.includes(job.id));
    }
  }
};

I've tried to do this, but it didn't work

 computed: {
      filteredJobs: function() {
        return this.jobs
          .filter(job => this.checkedUserIds.includes(job.userId))
          .filter(job => this.checkedIds.includes(job.id))
      }
    }

Upvotes: 2

Views: 246

Answers (1)

Phil
Phil

Reputation: 164742

Assuming that if no checkbox is checked for either of the filters, then you don't want to apply that filter, something like this should work...

computed: {
  filteredJobs () {
    return this.jobs.filter(({ id, userId }) => {
      return (this.checkedUserIds.length === 0 || this.checkedUserIds.includes(userId))
        && (this.checkedIds.length === 0 || this.checkedIds.includes(id))
    })
  }
}

Upvotes: 1

Related Questions