Vue-InstantSearch (Algolia): How to add ref= to input field?

573 views Asked by At

I would like to add a ref='foo' to the <ais-search-box> element (to the rendered input field), so I can then dynamically put .focus on it if needed. But how can I add the ref=[..]? My current code is:

<ais-search-box ref="foo">
    <div slot="submit-icon"><i class="fas fa-search text-xl p-2 text-blue-400"></i></div>
</ais-search-box>

But this is not working, the final rendered element does not contain any ref= info:

<form action="" role="search" novalidate="novalidate" class="ais-SearchBox-form">
   <input type="search" autocorrect="off" autocapitalize="off" autocomplete="off" spellcheck="false" required="required" maxlength="512" aria-label="Search" autofocus="autofocus" class="ais-SearchBox-input"> <button type="submit" title="Search" class="ais-SearchBox-submit">
    <div><i class="fas fa-search text-xl p-2 text-blue-400"></i></div></button> 
    <button type="reset" title="Clear" class="ais-SearchBox-reset" hidden="hidden">
    <svg role="img" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 20 20" class="ais-SearchBox-resetIcon"><path d="M8.114 10L.944 2.83 0 1.885 1.886 0l.943.943L10 8.113l7.17-7.17.944-.943L20 1.886l-.943.943-7.17 7.17 7.17 7.17.943.944L18.114 20l-.943-.943-7.17-7.17-7.17 7.17-.944.943L0 18.114l.943-.943L8.113 10z" fillRule="evenodd"></path></svg>
   </button> <!---->
</form>
1

There are 1 answers

1
Tony On

In the parent component, leave the ref on the child component as you have it.

Parent.vue

<ais-search-box ref="foo">
.....
</ais-search-box>

Child.vue

<form action="" ......>
   <input type="search" class="ais-SearchBox-input".. ref="childInput"> // add ref to the input field in the child component that you want to access
   .......
</form>

Accessing the input in the child component from the child component and putting focus on it:

this.$refs.childInput.focus();

Accessing the input in the child component from the parent component and putting focus on it:

this.$refs.foo.$refs.childInput.focus();