javascript - VueJS Filter Array Based on Input -


i have application , i'm trying filter array based on input form.

the problem array autocomplete isn't getting populated visitors match query of 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 repsonse axios populating previousvisitors array contains firstname of each previous visitor.

what doing wrong?

your v-model set visitor.first filtering based on firstname.

change code use v-model="visitor.firstname".

there other issues cause problems later. first dynamically adding value visitor. falls change detection caveat , value not reactive. should initialize value.

data: {   ...   visitor:{firstname: ''} } 

moreover, should use computed value filter. here 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>


Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -