I would like to be able to move focus from the input field in the parent component to the autosuggest list in a child component using the arrow down key.
I cannot get this to work. Tabbing works fine. If i use the this.$refs.suggestionButtons[0].focus(); in mounted the focus moves as soon as the autosuggest opens. I dont want this though. I only want the focus to be on the auto suggest when the arrow down key is clicked
Can anyone help with this please?
Component one (with input)
<input
class="form-control form-control-lg"
type="text"
v-on:keyup="autoSuggest"
v-model="search_input"
placeholder="Enter a keyword"
autocomplete="off"
id="search"
v-on:keyup.enter="showandSubmit"
/>
<CourseAutoSuggest
id="autoSuggestInput"
ref="autocomplete"
v-if="
search_input.length > 1 && suggestions.length > 0
"
:suggestions="suggestions"
:selected="selectedIndex"
v-on:suggest-click="autoSuggestQuery"
@close-dropdown="closeDropdown"
/>
</div>
Component Two (autosuggest)
<template>
<div v-if="showSuggestions" class="search-auto-suggest col-8 col-md-12">
<ul ref="suggestionsList">
<li v-for="(suggestion, index) in suggestions" :key="suggestion">
<button
ref="suggestionButtons"
@click="$emit('suggest-click', suggestion)"
@keyup.enter="$emit('suggest-click', suggestion)"
@keydown.arrow-up.prevent="moveFocusUp(index)"
@keydown.arrow-down.prevent="moveFocusDown(index)"
type="button"
:aria-selected="selectedIndex === index ? 'true' : 'false'"
>
{{ suggestion }}
</button>
</li>
</ul>
</div>
</template>
<script>
export default {
props: {
suggestions: Array,
},
data() {
return {
selectedIndex: null,
showSuggestions: true,
};
},
methods: {
moveFocusUp(index) {
if (index > 0) {
this.selectedIndex = index - 1;
this.$refs.suggestionButtons[this.selectedIndex].focus();
}
},
moveFocusDown(index) {
if (index < this.suggestions.length - 1) {
this.selectedIndex = index + 1;
this.$refs.suggestionButtons[this.selectedIndex].focus();
}
},
closeList(event) {
if (event.key === "Escape") {
this.showSuggestions = false;
this.$emit("close-list");
}
},
// focusInput() {
// this.$emit('focus-input');
// }
},
mounted() {
// Set initial focus
// this.$refs.suggestionButtons[0].focus();
// Listen for keydown events to close the list
this.$el.addEventListener("keydown", this.closeList);
},
beforeUnmount() {
this.$el.removeEventListener("keydown", this.closeList);
},
};
</script>