Home > Enterprise >  vue js filtering with search bar
vue js filtering with search bar

Time:10-31

I have created an app that requests from an API the data and creates flexboxes. Now I added a search box and I would like to filter the articles by their contact and/or title.

I've also created a computed property to filter the returned list of items but when I replace in line 11 the paginated('items') with paginated('filteredArticles') that returns nothing. What did I do wrong?

<template>
  <div id="app">
    <div class="search-wrapper">
      <input type="text" 
        class="search-bar" 
        v-model="search"
        placeholder="Search in the articles"/>
    </div>

    <paginate ref="paginator" class="flex-container" name="items" :list="items">
      <li v-for="(item, index) in paginated('items')" :key="index" class="flex-item">
        <div id="image"><img :src="item.image && item.image.file" /></div>
        <div id="date">{{ item.pub_date }}</div>
        <div id="title"> {{ item.title }}</div>
        <div class="article">{{item.details_en}}</div>
      </li>
    </paginate>

    <paginate-links for="items" :limit="2" :show-step-links="true"></paginate-links>
  </div>
</template>
    
<script>
import axios from "axios";

export default {
  data() {
    return {
      items: [],
      paginate: ["items"],
      search:'',
    };
  },
  created() {
    this.loadPressRelease();
  },
  methods: {
    loadPressRelease() {
      axios
        .get(`https://zbeta2.mykuwaitnet.net/backend/en/api/v2/media-center/press-release/?page_size=61&type=5`)
        .then((response) => {
          this.items = response.data.results;
        });
    },
  },
  computed:{
    filteredArticles() {
      return this.items.filter(item=>item.includes(this.search))
    }
  }
};
</script>

CodePudding user response:

Your computed doesn't seem correct. Since items is an array of objects, you'd need to do this:

filteredArticles() {
    if (!this.search) {
        return this.items;
    }
    return this.items.filter(item => {
        return item.title.includes(this.search);
    })
}

Note that this will only search the title field, and it's case sensitive.

CodePudding user response:

You need fields you want to search and connvert search string and fields with toLowerCase() or toUpperCase():

  computed : {
    filteredArticles() {
      if (!this.search) return this.items
      return this.items.filter(item => {
        return (item.title.toLowerCase().includes(this.search.toLowerCase()) || item.contact.toLowerCase().includes(this.search.toLowerCase()));
      })
    }
  }
  • Related