我有一个搜索下拉菜单,我希望这个键盘可以访问,我已经这样做了,但问题是当按下焦点下拉项目的上下箭头键时,它在控制台中给我一个错误,在图像下方。请任何人帮忙。它显示了我在 focusItem()
函数中的错误。我不知道我在这里做错了什么..
我该如何解决这个问题
<div x-data="keyboardAccess()" class="col-lg-8 offset-lg-2">
<fieldset class="searching-area">
<div class="input-group">
<input type="text"
@focus="isOpen = true"
@click.away="isOpen = false"
@keydown.escape.window="isOpen = false"
@keydown.arrow-up.prevent="startArrowKeys"
@keydown.arrow-down.prevent="startArrowKeys"
wire:model.debounce.500ms="searchProducts"
class="form-control"
placeholder="Search by name/SKU or scan barcode"
aria-describedby="productSearch" autofocus>
<span wire:loading wire:target="searchProducts" class="mr-1 search-combo-spinner spinner-border spinner-border-sm"></span>
<div class="input-group-prepend">
<span class="input-group-text" id="productSearch">
<i class="bx bx-search-alt"></i>
</span>
</div>
</div>
<div x-show="isOpen" class="search-results custom-scrollbar">
<ul x-ref="focusableDropdownItem">
@forelse ($searchProductResults as $variantKey => $productVariant)
<li>
<a href="#"
@if ($loop->first)
@keydown.arrow-down.prevent="focusNext({{ $productVariant->id }}, {{ $variantKey }})"
@elseif($loop->last)
@keydown.arrow-up.prevent="focusPrevious({{ $productVariant->id }}, {{ $variantKey }})"
@else
@keydown.arrow-down.prevent="focusNext({{ $productVariant->id }}, {{ $variantKey }})"
@keydown.arrow-up.prevent="focusPrevious({{ $productVariant->id }}, {{ $variantKey }})"
@endif
wire:click.prevent="addProductInTable({{ $productVariant->id }}, {{ $variantKey }})" style="color: inherit">
<div class="d-flex align-items-center justify-content-between">
<span>{{ $productVariant->product->name }} {{ $productVariant->variants === 'default' ? '' : '- '. $productVariant->variants }}</span>
@if (in_array($productVariant->id, $variantIds))
<span class="d-flex align-items-center">
<i class='bx bx-check-double text-success font-weight-bolder'></i>
Added
</span>
@endif
</div>
</a>
</li>
@empty
@if (strlen($searchProducts) >= 2)
<li>
<div>No result found</div>
</li>
@endif
@endforelse
</ul>
</div>
</fieldset>
</div>
<script>
function keyboardAccess() {
return {
isOpen: true,
focusedIndex: 0,
startArrowKeys() {
if (this.isOpen) {
this.focusItem()
}
},
focusPrevious(id, key) {
this.focusedIndex = this.focusedIndex - 1
this.focusItem()
document.addEventListener('livewire:load', () => {
this.addItemToArray(id, key)
})
},
focusNext(id, key) {
this.focusedIndex = this.focusedIndex + 1
this.focusItem()
document.addEventListener('livewire:load', () => {
this.addItemToArray(id, key)
})
},
addItemToArray(id, key) {
document.addEventListener('keydown', (e) => {
if (e.key === "Enter") {
e.preventDefault()
$wire.addProductInTable(id, key)
}
})
},
focusItem() {
this.$refs.focusableDropdownItem.children[this.focusedIndex].children[0].focus()
}
}
}
</script>