Search code examples
vue.jsalgoliavue-instant-search

Algolia Vue Instant Search – Toggling class is resetting attributes


I have an Algolia refinement list but each time I toggle a class around it, the query disappears. I can't work out what it is that is resetting the values.

Here is my current example:

<template>
  <div id="app" :class="{active}">
    <ais-instant-search :search-client="searchClient" index-name="products">
      <button @click="toggleActive">Toggle</button>
      <span>&larr; Pressing this is wiping the search.</span>
      <div class="dietary-requirements-dropdown--checkboxes">
        <ais-refinement-list attribute="dietary" :sort-by="['name:asc']"></ais-refinement-list>
      </div>
    </ais-instant-search>
  </div>
</template>

<script>
import algoliasearch from "algoliasearch/lite";

export default {
  name: "App",
  data() {
    return {
      active: false,
      searchClient: algoliasearch(
        "ZVIJ67X9P8",
        "df6c2515326327131df74c0a879b8794"
      )
    };
  },
  methods: {
    toggleActive() {
      this.active = !this.active;
    }
  }
};
</script>

<style lang="scss">
.dietary-requirements-dropdown--checkboxes {
  opacity: 1;
  .active & {
    opacity: 0.2;
  }
}
</style>

Demo here: https://codesandbox.io/s/vue-template-z5woy


Solution

  • As pointed out by @StevenB., the issue is the re-rendering of the dom elements, due to the reactive class names.

    Specifically, this attribute on the wrapper component:

    :class="{active}" 
    

    Rerenders all contents including this ais-refinement-list. This is a problem, as when the list is destroyed, the reactive search effectively treats all the non-existent checkboxes as not checked, resetting the search.

    It was a simple fix, while not perfectly reactive. I replaced:

    toggleActive() {
      this.active = !this.active;
    }
    

    With a "vanilla":

    toggleActive() {
      document.querySelector("#app").classList.toggle("active");
    }
    

    It would also be better to use $refs when available

    toggleActive() {
      this.$refs.filters.classList.toggle("active");
    }
    

    This means the DOM isn't re-rendered, the checkboxes aren't reset, and the search remains the same.