带有搜索过滤器的Vue.js嵌套循环

时间:2019-07-08 22:31:58

标签: javascript json vue.js search filter

我有一个带有嵌套对象的JSON对象,我正在对其进行迭代以提取数据。一切工作正常,但我想添加一个搜索/过滤器实现,以便在嵌套for循环的第二级上进行搜索。我有一些工作,但即时通讯没有得到任何数据返回。这是一个示例:

https://codesandbox.io/s/vue-template-s9t9o

在HelloWorld组件中进行搜索/过滤的位置。 如您所见,它在通过searchFilter方法后不输出其余数据。

要使其在没有搜索/过滤器的情况下工作,请在line #6上更改以下内容:

来自:<div class="contentSingle" v-for="(c, i) in searchFilter" :key="i">

收件人:<div class="contentSingle" v-for="(c, i) in cont" :key="i">

任何人都可以想到我可以做些什么?我需要按主数据对象中每个content中的元素进行过滤。您可以在FauxData/dataContent.js目录中找到数据对象。

非常感谢。

-S

1 个答案:

答案 0 :(得分:1)

您应该使用方法而不是计算方法:

class AddressExample(models.Model):
    id_address = models.ForeignKey(Address, unique=True,on_delete=models.PROTECT)
    id_person = models.ForeignKey(Person, blank=True, null=True, unique=True, on_delete=models.PROTECT)
    id_company = models.ForeignKey(Person, blank=True, null=True, unique=True, on_delete=models.PROTECT)

   class Meta:
       unique_togther = ('id_address', 'id_person', 'id_company')
       # Not sure if it will throw a error here because `id_person` and `id_company` can be blank 
       # or null. But the use of `unique together` is for cases where you want to guarantee 
       # the combination of the primary keys will be unique.

,然后使用HTML代码:

  methods: {
    filterValue(content) {
      return content.filter(item => {
        let itemUpper = item.content.toUpperCase();
        let searchUpper = this.search.toUpperCase();
        return itemUpper.indexOf(searchUpper) > -1;
      });
    }
  }

已更新

如果要隐藏空白部分,请使用计算值:

  <section id="content">
    <input type="text" id="search" name="search" v-model="search" placeholder="Search Content...">
    <div v-for="(cont, index) in content" :key="index" class="contentWrapper">
      <h1>{{ index }}</h1>
      <div class="contentSingle" v-for="(c, i) in filterValue(cont)" :key="i">
        <h3>{{ c.title }}</h3>
        <div v-html="c.content"></div>
      </div>
    </div>
  </section>

在外部v-for中使用 computed: { filteredData() { return Object.keys(this.content).reduce((a, cKey) => { const data = this.filterValue(this.content[cKey]); if (data.length) { a[cKey] = data; } return a; }, {}); } }, methods: { filterValue(content) { return content.filter(item => { let itemUpper = item.content.toUpperCase(); let searchUpper = this.search.toUpperCase(); return itemUpper.indexOf(searchUpper) > -1; }); } }

filteredData

codepen上的演示