[Vuejs]-Vue js: search filter according to multiple attributes not working properly

0👍

You can use || to check for the search result in other fields:

new Vue({
  el:"#app",
  data() {
    return {
      search: '',
      questions: [
        { 
          questionTitle: "title1", 
          name: "name1", 
          desc: "desc1",
          categories: [
            { category_name: "category1a" },
            { category_name: "category1b" }
          ]
        },
        { 
          questionTitle: "title2", 
          name: "name2", 
          desc: "desc2",
          categories: [
            { category_name: "category2a" },
            { category_name: "category2b" }
          ]
        },
        { 
          questionTitle: "title3", 
          name: "name3", 
          desc: "desc3",
          categories: [
            { category_name: "category3a" },
            { category_name: "category3b" }
          ]
        }
      ]
    }
  },
  computed: {
    filteredList() {
      const search = this.search;
      return search===''
        ? this.questions
        : this.questions.filter(question => 
            question.questionTitle.includes(search) ||
            question.name.includes(search) ||
            question.desc.includes(search) ||
            question.categories.some(category =>
              category.category_name.includes(search)
            )
          )
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
 <div class="search-wrapper">
   <label>Search title:</label>
   <input type="text" v-model="search" placeholder="Search title.."/>
  </div>
  <ul  class="container-question">
    <li v-for="(question,questionIndex) in filteredList" :key="questionIndex">
      {{question.questionTitle}} - {{question.name}} - {{question.desc}}
      <div 
        class="category"               
        v-for="(allCategories, categoryIndex) in question.categories"           
        v-bind:key="categoryIndex"
      >               
        <mark> {{ allCategories.category_name }} </mark>             
      </div>
    </li>
  </ul>
</div>

Leave a comment