I am trying to make an autocomplete input and I want to filter the results, it filters but only the first object it finds and I need it to find for example all the ones that start with p
could you support me please
new Vue({
el: '#app',
data: {
value: '',
routes: [
{ id: 1, name: "perfil" },
{ id: 2, name: "perfil2" },
{ id: 3, name: "menu"},
{ id: 4, name: "menu2"}
],
filter: []
},
methods: {
filterResults ( value ) {
const search = this.routes.filter(route => route.name === value);
this.filter = search
console.log(search)
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input type="text" v-model="value" placeholder="Buscar" @input="filterResults(value)"/>
<li v-for="(route, id) in filter" :key="id">{{ route.name }}</li>
</div>
You have the problem in the
filter()
. You are looking for an exact match of the entered word. To search for those that "begin with P" you can usestartsWith()
.On the other hand, to make the search case insensitive, I compare the names to the value entered, but make both lowercase with
toLowerCase()
.You can use match (which returns all the values that P contains), it doesn't matter if it's in the middle, end or beginning or startsWith