I am writing a job filtering system in Vuejs and when the user enters a letter in the search bar, it only filters through the first letter instead of the whole word.
Imagine I have a list with item "Banana". If the user types "Banana" into the search bar, the item "Banana" is returned, since the search matches the list item. When the user just types a singular letter i.e. "B" it displays all items with the letter B. However when another letter is followed by that "Ba" it returns nothing.
Below is the code that is causing me problems:
<script>
export default {
data(){
return{
searchQuery:'',
selectedItem: null,
isVisible: false,
userArray: [],
};
},
computed: {
filteredUser() {
const query = this.searchQuery.toLowerCase();
if(this.searchQuery === "" ) {
return this.userArray;
}
return this.userArray.filter((user) => {
return Object.values(user).some((word) =>
String(word).toLowerCase().includes(query)
);
});
},
},
Other aspects of this filter function are working (i.e. the ability to click on jobs) except this search function.
Any help would be greatly appreciated.
CodePudding user response:
Your code seems to work. Check your v-model
directive.
new Vue({
el: "#app",
data(){
return{
searchQuery:'',
selectedItem: null,
isVisible: false,
userArray: [{name: "foo"}, {name: "bar"}, {name: "baz"}],
};
},
computed: {
filteredUser() {
const query = this.searchQuery.toLowerCase();
if(this.searchQuery === "" ) {
return this.userArray;
}
return this.userArray.filter((user) => {
return Object.values(user).some((word) =>
String(word).toLowerCase().includes(query)
);
});
},
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input v-model="searchQuery" />
<p>{{filteredUser}}</p>
</div>
CodePudding user response:
You can simply achieve this with the help of String.startsWith()
along with the Array.filter()
method.
Live Demo :
new Vue({
el: "#app",
data(){
return{
searchQuery:'',
selectedItem: null,
isVisible: false,
userArray: [{name: "Alpha"}, {name: "Beta"}, {name: "Basu"}, {name: "Amar"}],
};
},
computed: {
filteredUser() {
const query = this.searchQuery.toLowerCase();
if(!query) {
return this.userArray;
}
return this.userArray.filter(user => user.name.toLowerCase().startsWith(query));
},
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input v-model="searchQuery" />
<p>{{ filteredUser }}</p>
</div>