Search code examples
vue.jsvuejs2vue-cli-3

Vue custom search filter doesn't match with v-model value


This is my code :

<input type="text" v-model="searchInput">
<ul>
   <li v-for="(badge, index) in filterBadges" :key="index"></li>
</ul>

And my computed function :

data() {
  return {
    searchInput: '',
    badges: [
      'JS', 'BitBucket'
    ]
  }
},
computed: {
  filterBadges() {
    return this.badges.filter((badge) => {
      return badge.match(this.searchInput)
    });
  }
}

When searchInput is empty shows all items in the array but when I type something matching with the array items, It shows empty array. Any help will be appreciated.


Solution

  • Match method on string accepts only regular expression: see mdn docs

    I would do it oldschool way instead:

    filterBadges() {
        return this.searchInput === '' ? 
            this.badges : 
            this.badges.filter(badge => badge.toLowerCase().indexOf(this.searchInput.toLowerCase()) > -1);
      }