【问题标题】:How to filter array of data with by category?如何按类别过滤数据数组?
【发布时间】:2020-05-22 17:01:15
【问题描述】:

这是我在 Nuxt js 上的 vue 页面:

<template> 
  <div>
   <select
    id="category"
    name="category"
    v-model="selected">
     <option value="0">categories</option>
     <option value="1">1</option>
     <option value="2">2</option>
   </select>
   <services-list :list="services.list" /> 
 </div>
<template>

export default {
  components: {
    ServicesList
  },
  data() {
    return {
      services: {
        list: [
          {
            name: 'NAME1',
            title: 'TITLE1',
            category: '1'
          },
          {
            name: 'NAME2',
            title: 'TITLE2',
            category: '2'
          },
         }
        }
       }

我需要根据来自&lt;select&gt; 的选定类别过滤呈现的数据。 我尝试在更改&lt;select&gt; 时更改状态,但它只在第一次起作用。因为 state 中的数据会发生变化,第二次运行它不会给出正确的结果。

【问题讨论】:

    标签: vue.js vuex nuxt.js


    【解决方案1】:

    要从selected 中获取过滤后的list,请使用computed

    computed{
      filtered(){
        if (this.selected === null) return this.services.list
        return this.services.list.filter(s => s.category === this.selected)
      }
    }
    

    然后你可以在你的模板中使用filtered

    【讨论】:

    • 我无法在 computed 中访问 v-model (this.selected),为什么?
    • 我的意思是 this.selected 在 filters() 中总是未定义
    • @hesamsameni 格式错误的答案。删除重复的 return 语句。
    • 我想通了,这个答案返回 true 或 false,我想要整个对象,所以我将 .map() 替换为 .filter()
    【解决方案2】:
      computed: {
        filtered() {
          if (this.selected === null) return this.services.list
          return this.services.list.filter(obj => obj.category === this.selected)
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2021-11-15
      • 2021-11-15
      • 2019-03-25
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      相关资源
      最近更新 更多