I have built an app with VueJS 3 (Composition API) and the Quasar framework (2.14.5) and integrated Algolia (4.24.0) as my search engine (with vue-InstantSearch 4.8.4). It works as a charm.
In a next step I have built a Vue component to use Algolia’s autocomplete following the guidelines on the Algolia website. My goal is to have a search with dropdown to search for companies in my Algolia ‘companies’ index. I face 2 issues currently:
- The dropdown shows applicable values when I start typing, so that works, but when I select a value from the suggestions with the mouse or by hitting Enter, the search field doesn’t get populated with the selected value. I have no idea why, because all sandbox examples I have seen work properly.
- I don’t know how to log to the console what the value is that is selected from the suggestions in the dropdown.
Can you help?
My Vue component:
<template>
<div id="autocomplete" />
</template>
<script setup>
import { algoliaSearchClient } from 'boot/algolia'
import { autocomplete, getAlgoliaResults } from '@algolia/autocomplete-js'
import { onMounted, onBeforeUnmount } from 'vue'
import '@algolia/autocomplete-theme-classic'
const INDEX_NAME = 'companies'
let autocompleteInstance = null
onMounted(async () => {
if (autocompleteInstance) {
autocompleteInstance.destroy()
}
autocompleteInstance = autocomplete({
container: '#autocomplete',
placeholder: 'Search company',
getSources ({ query }) {
return [{
sourceId: INDEX_NAME,
// getItemInputValue: ({ item }) => item.query,
getItems () {
const results = getAlgoliaResults({
searchClient: algoliaSearchClient,
queries: [{
indexName: INDEX_NAME,
query,
params: {
hitsPerPage: 5,
attributesToSnippet: [],
attributesToHighlight: ['name', 'city', 'country.label'],
snippetEllipsisText: '…'
}
}]
})
// console.log('Algolia results: ', results)
return results
},
templates: {
item ({ item, components, html }) {
return html`
<div class="aa-ItemWrapper">
<div class="aa-ItemContent">
<div class="aa-ItemContentBody">
<div class="aa-ItemContentTitle">
${components.Highlight({
hit: item,
attribute: 'name'
})}
</div>
<div class="aa-ItemContentDescription">
${components.Highlight({
hit: item,
attribute: 'city'
})}
</div>
</div>
<div class="aa-ItemActions">
<button
class="aa-ItemActionButton aa-DesktopOnly aa-ActiveOnly"
type="button"
title="Select"
>
<svg
viewBox="0 0 24 24"
width="20"
height="20"
fill="currentColor"
>
<path
d="M18.984 6.984h2.016v6h-15.188l3.609 3.609-1.406 1.406-6-6 6-6 1.406 1.406-3.609 3.609h13.172v-4.031z"
/>
</svg>
</button>
</div>
</div>
</div>
`
}
}
}]
}
})
})
onBeforeUnmount(() => {
if (autocompleteInstance) {
autocompleteInstance.destroy()
}
})
</script>
The dropdown in the UI: