自定义细化列表时 Algolia 和 VueJs 的计时问题

Timing issue with Algolia and VueJs when customising the refinement list

我正在使用 Algolia 建立过滤器的细化列表,并且我自定义了 algolia 实例以显示没有匹配项的方面:Algolia docs on displaying facets with no matches

我遇到的问题是,在 VueJs 的挂载函数中,Algolia 正在构建细化列表,然后施展魔法来构建 Dom。我遇到一个问题,我试图在同一个安装函数中将 CSS class 附加到这些元素,但我正在处理的 NodeList 不断返回 [] 空。

我的解决方案在打字和使用优化列表时完全有效,但由于时间不同步,它在页面重新加载时不起作用。

  mounted() {
    this.searchClient
      .searchForFacetValues([
        {
          indexName: this.indexName,
          params: {
            facetName: this.brandAttribute,
            facetQuery: '',
            maxFacetHits: this.brandLimit,
          },
        },
      ])
      .then(([{ facetHits }]) => {
        this.initialFacets.push(
          ...facetHits.map(facet => ({
            ...facet,
            label: facet.value,
            value: facet.value,
            isRefined: false,
            count: 0,
          }))
        );
      });

      console.log(this.$el.querySelectorAll(".ais-RefinementList-list .ais-RefinementList-count"));  //Returns empty

      setTimeout(() => {
        console.log(this.$el.querySelectorAll(".ais-RefinementList-list .ais-RefinementList-count")); //Is populated
      }, 5000);
  },

我已经设置了超时来证明这是一个时间问题。在我的超时内节点列表按预期返回,我可以添加我的 CSS class,但我要等多久?我不认为这是一个正确的解决方案

我已经尝试了所有 VueJs 生命周期钩子,并且所有 NodeList 都返回 null。

我需要的是:

页面完全加载后,遍历我的 nodeList 并添加 CSS。我这样做的方式是:

document.querySelectorAll(".ais-RefinementList-list .ais-RefinementList-count").forEach(
        function(x) {

          if(x.innerHTML == 0) {
            x.parentElement.style.backgroundColor = "red"
          } else {
            x.parentElement.style.backgroundColor = "white"
          }
        }
      );

工作解决方案:

页面刷新,时间问题:

将代码置于超时状态:

setTimeout(() => {
        this.$el.querySelectorAll(".ais-RefinementList-list .ais-RefinementList-count").forEach(
          function(x) {

            if(x.innerHTML == 0) {
              x.parentElement.style.backgroundColor = "red"
            } else {
              x.parentElement.style.backgroundColor = "white"
            }
          }
        );
      }, 5000);

5 秒后给出此解决方案:工作:

我能够通过自定义 UI 的解决方案来克服这个问题:Algolia docs, customizing the UI

我完全重写了我的优化列表,并使用 :style 绑定指令有条件地添加了所需的 类。

<ais-refinement-list
  attribute="ParentPageTitle"
  :transformItems="transformItems"
>

  <label 
    slot="item"
    slot-scope="{ item }"
    class="ais-RefinementList-label"
    :style="[item.count ? {'background-color' : 'white'} : {'background-color' : 'red'}]"
  >
    <input type="checkbox" class="ais-RefinementList-checkbox">
    <span class="ais-RefinementList-labelText">{{item.value}}</span>
  </label>
</ais-refinement-list>

CSS 现在可以在运行时正确设置组件的样式,并且计时问题已得到解决