<template> <v-autocomplete v-model="select" :loading="loading" :items="items" :search-input.sync="search" item-text="label" return-object hide-no-data hide-details label="Søk..." solo auto-select-first placeholder="Søk..." ref="autocomplete" > <template v-slot:item="data"> {{data.item.label + ' (' + (data.item.lang_set ? Array.from(data.item.lang_set).sort().join(', ') : 'fritekstsøk' ) + ')'}} </template> </v-autocomplete> </template> <script> import axios from "axios" export default { props: { endpoint: String }, data: function() { return { loading: false, items: [], search: null, select: null } }, watch: { search (val) { val && val !== this.select && this.run_query(val) }, select(item) { this.$emit('submit', item) } }, methods: { run_query(q) { let self = this this.loading = true return axios.get(self.endpoint + 'suggest?q=' + encodeURIComponent(q)) .then( function(response) { let hits = [] response.data.forEach((item, i) => { let match = encodeURIComponent(item.match) if (! hits[0] || hits[0].word != match) { hits.splice(0, 0, {q: encodeURIComponent(q), lang_set: new Set(), word: match, articles: []}) } hits[0].lang_set.add(item.dictionary == 'bob' ? 'bm' : 'nn') hits[0].articles.push(item) }); hits.forEach(function (hit) { if (hit.lang_set) { hit.label = decodeURIComponent(hit.word) } }); hits.reverse() hits = hits.slice(0, 5) if (q) { hits.push({q: encodeURIComponent(q), label: q + ' '}) } self.items = hits self.loading = false }) } }, } </script> <style scoped> div.v-input { margin: 0px; } </style>