2

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))
      }
    }
1
  • What "didn't work" about your filteredJobs computed property? You could probably combine the conditions into a single .filter() but it looks like it should work as-is Commented Oct 25, 2019 at 6:38

1 Answer 1

1

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))
    })
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.