【问题标题】:Filtering json response in Vue在 Vue 中过滤 json 响应
【发布时间】:2021-03-10 01:49:04
【问题描述】:

我在过滤 Vue 中的 json 响应时遇到问题。

return this.offers.filter(type => type.offers == 'Junior');

每当我将其保留为 return this.offers 时,都会在我的 html 中显示:

{"-MN5agCddYAdy7c8GSSz": { "companyName": "dawdwad", "image": "da", "jobDescription": "dada", "location": "daw", "salary": "dadaw", "skill": "dawda", "tags": "dada", "title": "dwa" }, "-MN7vsTsNohgQigd3S26": { "companyName": "ejadfjaq", "image": "", "jobDescription": "dada", "location": "2sjawdja", "salary": "40324032", "skill": "Junior", "tags": "ux", "title": "fawd" } }

但我只想显示带有"skill": "Junior" 的字段。

【问题讨论】:

    标签: javascript json vue.js vuejs2 vue-component


    【解决方案1】:

    您的 JSON 是一个对象,但 filter 仅适用于数组。您可以在计算中使用for...in 循环来重新格式化它并按照您喜欢的方式对其进行过滤:

    computed: {
      filteredOffers() {
        const filteredOffers = [];
        for(const key in this.offers) {
          if (this.offers[key].skill == 'Junior') filteredOffers.push(this.offers[key]);
        }
        return filteredOffers;
      }
    }
    

    这将返回您想要的对象数组。如果您只想在模板中显示它们:

    <div id="app">
       {{ filteredOffers }}
    </div>
    

    这是一个演示:

    new Vue({
      el: "#app",
      data() {
        return {
          offers: {
            "-MN5agCddYAdy7c8GSSz": {
              "companyName":"dawdwad",
              "image":"da",
              "jobDescription":"dada",
              "location":"daw",
              "salary":"dadaw",
              "skill":"dawda",
              "tags":"dada",
              "title":"dwa"
            },
            "-MN7vsTsNohgQigd3S26":{
              "companyName":"ejadfjaq",
              "image":"",
              "jobDescription":"dada",
              "location":"2sjawdja",
              "salary":"40324032",
              "skill":"Junior",
              "tags":"ux",
              "title":"fawd"
            }
          }
        }
      },
      computed: {
        filteredOffers() {
          const filteredOffers = [];
          for(const key in this.offers) {
            if (this.offers[key].skill == 'Junior') filteredOffers.push(this.offers[key]);
          }
          return filteredOffers;
        }
      },
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
       {{ filteredOffers }}
    </div>

    【讨论】:

    • 谢谢。还有一个问题。如果我有一个带有下拉按钮的组件,而在另一个组件中我获取数据并显示它。如何通过只有下拉按钮的组件过滤数据?
    • 不客气。有几种方法可以在组件之间共享数据。如果组件在简单的父子关系中不相关,Vuex 是最好的解决方案。
    猜你喜欢
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 2020-03-09
    • 2019-08-02
    • 2018-12-03
    相关资源
    最近更新 更多