Reputation: 2370
I have a vuejs application and I'm trying to filter an array based on an input from a form.
The problem is my array autocomplete
isn't getting populated with the visitors that match the query of the first name.
My HTML
<input class="input" placeholder="First Name" v-model="visitor.first" @keyup.enter="searchVisitors">
My Vue Instance
new Vue({
el: '#app',
data: {
previousVisitors: [],
autocomplete: [],
visitor: {}
},
mounted() {
axios.get('/visitors/all').then(response => this.previousVisitors = response.data);
},
methods: {
searchVisitors(){
var q = this.visitor.first;
this.autocomplete = this.previousVisitors.filter(item => {return item.firstName === q});
console.log(this.autocomplete);
}
}
});
I can confirm the repsonse from the axios which is currently populating the previousVisitors
array contains the firstName
of each previous visitor.
What am I doing wrong?
Upvotes: 3
Views: 3879
Reputation: 82459
Your v-model
is set to visitor.first
but you are filtering based on firstName
.
Change your code to use v-model="visitor.firstName"
.
There are some other issues that could cause problems later. First you are dynamically adding a value to visitor
. That falls into a change detection caveat and that value will not be reactive. You should initialize that value.
data: {
...
visitor:{firstName: ''}
}
Moreover, you should really use a computed value for the filter. Here is a complete example.
console.clear()
const visitors = [{
firstName: "bob"
},
{
firstName: "mary"
},
{
firstName: "susan"
},
{
firstName: "Phillip"
},
]
new Vue({
el: '#app',
data: {
previousVisitors: [],
visitor: {
firstName: ''
}
},
mounted() {
// axios.get('/visitors/all').then(response => this.previousVisitors = response.data);
setTimeout(() => this.previousVisitors = visitors)
},
computed: {
autocomplete() {
return this.previousVisitors.filter(v => v.firstName === this.visitor.firstName)
}
}
});
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
<input class="input" placeholder="First Name" v-model="visitor.firstName"> {{autocomplete}}
</div>
Upvotes: 2