VueJS filter array based on input
I have a vuejs application and I am trying to filter an array based on input from a form.
The problem is my array is autocomplete
not getting populated by visitors who match the request for 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 answer from the axioms, which is currently populating an array previousVisitors
that contains firstName
every previous visitor.
What am I doing wrong?
source to share
Yours is v-model
set to visitor.first
, but you're filtering based on firstName
.
Change your code to use v-model="visitor.firstName"
.
There are other problems that can cause problems later. First, you dynamically add the value to visitor
. This refers to changing detection bypass and this value will not be reactive. You must initialize this value.
data: {
...
visitor:{firstName: ''}
}
Also, you should actually use the computed value for the filter. Here's 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/vue@2.2.6/dist/vue.js"></script>
<div id="app">
<input class="input" placeholder="First Name" v-model="visitor.firstName"> {{autocomplete}}
</div>
source to share