algoliainstantsearch.jsvue-instant-search

Hide default message of ais-state-results widget


I am using ais-instant-search and ais-state-results to display my data. I hide the result until query.length > 0. It works but if I don't enter any search string, it always shows a message. Below are my code and screenshot:

enter image description here

<ais-state-results>
            <p slot-scope="{ query, hits }" v-if="!hits.length">
                Not found for: <q>{{ query }}</q>
            </p>
            <template v-else slot-scope="{ query }">
                <ais-hits v-if="query.length > 0">
                    <template slot="item"
                            slot-scope="{ item }"
                    >
                        <h1>
                            <ais-highlight
                                    :hit="item"
                                    attribute="name"
                            />
                        </h1>

                        <ul>
                            <li>{{ item.price }}</li>
                        </ul>

                    </template>
                </ais-hits>
            </template>
        </ais-state-results>

Solution

  • The widget <ais-state-results> contains a fallback content which renders when the default slot is empty (this is the screenshot you gave). Both conditions you've written inside your example are false once the App starts. Since nothing is rendered inside the slot the default one kicks in. You can solve this issue with an empty div when none of the conditions are met. Here is an example:

    <ais-state-results>
      <template slot-scope="{ query, hits }">
        <!-- First condition -->
        <p v-if="!hits.length">Not found for: <q>{{ query }}</q></p>
        <!-- Second condition -->
        <ais-hits v-else-if="query" />
        <!-- Fallback condition -->
        <div v-else />
      </template>
    </ais-state-results>
    

    You can find a live example on CodeSandbox.