Conditional Display in Vue InstantSearch
On this page
Handling no results
Not all queries lead to results, and it’s important to let users know when this happens. This gives you an opportunity to provide hints on how to adjust the query. This way, you can ensure users don’t leave your website or search using an external search engine.
Display a message
The easiest way to display a fallback message when a query doesn’t return results is to use the ais-state-results
widget.
1
2
3
4
5
6
7
8
<ais-state-results>
<template v-slot="{ results: { hits, query } }">
<ais-hits v-if="hits.length > 0" />
<div v-else>
No results have been found for {{ query }}.
</div>
</template>
</ais-state-results>
Note that the above example also works with ais-infinite-hits
.
Let the user clear all filters
Users make mistakes, which can cause them to not find any results. You can account for this by providing a way to clear filters right from the “no results” state, so they can start over.
You can achieve this with the ais-clear-refinements
widget. You can also add :excluded-attributes="[]"
to clear the query as well.
1
2
3
4
5
6
7
8
9
10
11
<ais-state-results>
<template v-slot="{ results: { hits } }">
<ais-hits v-if="hits.length > 0" />
<div v-else>
No results have been found for {{ query }}.
<ais-clear-refinements :excluded-attributes="[]">
<template v-slot:resetLabel>Clear all refinements</template>
</ais-clear-refinements>
</div>
</template>
</ais-state-results>
You can also use ais-current-refinements
to show the currently applied refinements.
1
2
3
4
5
6
7
8
9
<ais-state-results>
<template v-slot="{ results: { hits } }">
<ais-hits v-if="hits.length > 0" />
<div v-else>
No results have been found for {{ query }}.
<ais-current-refinements :excluded-attributes="[]" />
</div>
</template>
</ais-state-results>
Handling the empty query
By default, Vue InstantSearch always shows you results, even when the query is empty. Depending on your use case and the way you want to build your UI, you may want to only show results when there’s a query.
1
2
3
4
5
<ais-state-results>
<template v-slot="{ state: { query } }">
<ais-hits v-if="query.length > 0" />
</template>
</ais-state-results>