Skip to content

Instantly share code, notes, and snippets.

@jensgro
Last active October 8, 2019 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jensgro/3e1d95c2e936fd01a2924580d1c635b8 to your computer and use it in GitHub Desktop.
Save jensgro/3e1d95c2e936fd01a2924580d1c635b8 to your computer and use it in GitHub Desktop.
Vue.JS AJAX Autocomplete
<div id="app">
<form>
<div class="input-group">
<input type="text" class="form-control" placeholder="Buchtitel" aria-label="Buchtitel suchen" v-model="query" @keyup="search">
<div class="input-group-append"><button class="btn btn-outline-primary" id="button">Suchen</button></div>
</div>
<div class="p-5 d-flex justify-content-center" v-if="!docs.length && query.length"><div class="spinner-border" role="status"><span class="sr-only">Loading...</span></div></div>
<div class="list-group" v-if="docs.length">
<button v-for="doc in docs" type="button" class="list-group-item list-group-item-action">{{ doc.title }}</button>
</div>
</form>
</div>
const app = new Vue({
el: '#app',
data: {
query: "",
docs: [],
controller: null,
},
methods: {
search() {
if(controller) {
controller.abort();
}
this.controller = new AbortController();
if(this.query.length > 5) {
fetch(`https:/openlibrary.org.search.json?title=${this.query.replace(/\s/, '+')}`)
.then(res => res.json())
.then(
this.docs = res.docs;
this.controller = null;
)
}
}
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
#app {
padding: 1em;
}
.list-group {
max-height: 15.375rem;
overflow: scroll;
-webkit-overflow-scrolling: touch;
}
.d-flex[hidden] {
display: none !important;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment