Using Autocomplete with Vue
Learn how to embed Autocomplete into a Vue application.
You can integrate an Autocomplete instance into a Vue application using Vue's Composition API. Specifically you can instantiate an Autocomplete instance in the onMounted
lifecycle hook in the setup
function.
This example uses an Algolia index of e-commerce products as a source. You could use any other source or sources you like.
#
PrerequisitesThis tutorial assumes that you have:
- an existing Vue (v3) application where you want to implement the autocomplete menu
- familiarity with the basic Autocomplete configuration options
note
Since Vue's Composition API is available starting in Vue 3, you can only use this guide for Vue 3 applications.
#
Getting startedBegin by adding a container for your autocomplete menu. This example adds a div
with autocomplete
as an id
.
Then, import the necessary packages for a basic implementation. Since the example queries an Algolia index, it imports the algoliasearch
package, autocomplete
and getAlgoliaHits
from the autocomplete-js
package. Finally, it imports autocomplete-theme-classic
package for some out of the box styling.
Depending on your desired sources, you may need to import other packages including plugins.
Include some boilerplate to insert the autocomplete into:
#
Adding an Algolia sourceThe autocomplete-js
package provides a built-in getAlgoliaHits
function for querying an Algolia index. It requires an Algolia search client initialized with an Algolia application ID and API key. It lets you search into your Algolia index using an array of queries
, which defines one or more queries to send to the index.
For more information how to use the getAlgoliaHits
function, see the Getting Started guide.
#
Mounting the autocompleteYou can instantiate and mount your Autocomplete instance in the onMounted
lifecycle hook in the setup
function. Doing so requires passing the renderer
and render
parameters.
This is because the default Autocomplete implementation uses Preact's version of createElement
, Fragment
and render
. Without providing Vue's version of these, the Autocomplete instance won't render the views properly.
#
Customizing templatesNext, to display the results from Algolia, you need to define an item
template. If you're using the highlighting and snippeting utilities, there's one thing to keep in mind: you must pass them Vue's createElement
function. Without doing this, the utilities default to preact.createElement
and won't work properly.
The highlighting and snippeting utilities are:
Here's an example of a custom item
template using snippetHit
:
Keep in mind that you should use JSX syntax for your templates.
#
Further UI customizationIf you want to build a custom UI that differs from the autocomplete-js
output, check out the guide on creating a custom renderer. This guide outlines how to create a custom React renderer, but the underlying principles are the same for any other front-end framework.