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?
-
What's not working as you expect?Bert– Bert2017年07月28日 15:22:27 +00:00Commented Jul 28, 2017 at 15:22
-
I've updated the question, sorry. It's the array "autocomplete" it's not populating the array based on the first name.Dev.W– Dev.W2017年07月28日 15:25:38 +00:00Commented Jul 28, 2017 at 15:25
1 Answer 1
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>