使用Vue和复选框过滤列表?

时间:2018-10-25 16:53:34

标签: javascript vue.js vuejs2

我正在尝试使用复选框中的userId筛选帖子列表。我正在从https://jsonplaceholder.typicode.com/posts中提取数据,然后想添加复选框,当选中该复选框时,将按userId过滤列表。这是我目前所拥有的:

var app = new Vue({
  el: '#app',
  data() {
    return {
      jobs: [],
      userIds: ['1', '2', '3'],
      checkedUserIds: []
    }
  },
  created() {
    axios
      .get('https://jsonplaceholder.typicode.com/posts')
      .then(response => (this.jobs = response.data))
  },
  computed: {
    filteredJobs() {
      if (!this.checkedUserIds.length)
        return this.jobs
      return this.jobs.filter(job => this.checkedUserIds.includes(job.userId))
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">

  <div v-for="userId in userIds">
    <input type="checkbox" v-model="checkedUserIds" v-bind:value="userId" /> {{userId}}
  </div>

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

我很困惑为什么当我单击一个复选框时整个列表消失而不是按userId进行过滤

1 个答案:

答案 0 :(得分:4)

您的userIds: ['1', '2', '3'],是一个字符串数组,而不是整数。尝试userIds: [1, 2, 3],

json文件的userId为整数。类型必须相同才能使该功能正常工作。

var app = new Vue({
  el: '#app',
  data() {
    return {
      jobs: [],
      userIds: [1,2,3],
      checkedUserIds: []
    }
  },
  created() {
    axios
      .get('https://jsonplaceholder.typicode.com/posts')
      .then(response => (this.jobs = response.data))
  },
  computed: {
    filteredJobs() {
      if (!this.checkedUserIds.length)
        return this.jobs
      return this.jobs.filter(job => this.checkedUserIds.includes(job.userId))
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">

  <div v-for="userId in userIds">
    <input type="checkbox" v-model="checkedUserIds" v-bind:value="userId" /> {{userId}}
  </div>

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