直接使用vxe-table中的vxe-pulldown组件无法实现上下键切换元素,回车选中,解决方案如下:
1.vxe-grid开启键盘导航,开启当前行选中
rowConfig: {
isCurrent: true
},
keyboardConfig: {
isArrow: true
}
2.下拉容器显示面板后,调用vxe-grid的focus方法使表格聚焦
$pulldown?.showPanel()
xGrid.value?.focus()
3.监听vxe-grid的键盘事件,回车时选中赋值给vxe-input
const keydownEvent1 = (e:any) =>{
const $pulldown = xDown.value
if(e.$event.keyCode === 13){
const row = xGrid.value?.getCurrentRecord()
demo.value = row.name
$pulldown?.hidePanel()
xGrid.value?.clearCurrentRow()
xGrid.value?.blur()
}
}
4. 下拉容器收起时,清除选中行且使vxe-grid失焦
$pulldown?.hidePanel()
xGrid.value?.clearCurrentRow()
xGrid.value?.blur()
完整示例代码如下:
<template>
<vxe-pulldown ref="xDown" transfer>
<template #default>
<vxe-input v-model="demo.value" @keydown="keydownEvent" @focus="focusEvent" @click="clickEvent"/>
</template>
<template #dropdown>
<div class="my-dropdown">
<vxe-grid
height="auto"
ref="xGrid"
:row-config="{isHover: true,isCurrent: true}"
:keyboard-config="{isArrow: true}"
:data="demo.tableData"
:columns="demo.tableColumn"
@cell-click="cellClickEvent"
@keydown="keydownEvent1"/>
</div>
</template>
</vxe-pulldown>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { VxePulldownInstance, VxeGridInstance } from 'vxe-table'
const demo = reactive({
value: '',
tableColumn: [
{ field: 'name', title: 'Name' },
{ field: 'role', title: 'Role' },
{ field: 'sex', title: 'Sex' }
],
tableData: [] as any[],
tableList: [
{ name: 'Test1', role: '前端', sex: '男' },
{ name: 'Test2', role: '后端', sex: '男' },
{ name: 'Test3', role: '测试', sex: '男' },
{ name: 'Test4', role: '设计师', sex: '女' },
{ name: 'Test5', role: '前端', sex: '男' },
]
})
const xDown = ref<VxePulldownInstance>()
const xGrid = ref<VxeGridInstance>()
const focusEvent = async() => {
const $pulldown = xDown.value
setTimeout(() => {
if (demo.value) {
demo.tableData = demo.tableList.filter((row) => row.name.indexOf(demo.value) > -1)
} else {
demo.tableData = demo.tableList.slice(0)
}
}, 100)
await $pulldown?.showPanel()
xGrid.value?.focus()
}
const keydownEvent = (e:any) => {
setTimeout(() => {
if (demo.value) {
demo.tableData = demo.tableList.filter((row) => row.name.indexOf(demo.value) > -1)
} else {
demo.tableData = demo.tableList.slice(0)
}
}, 100)
}
const clickEvent = () => {
const $pulldown = xDown.value
$pulldown?.showPanel()
xGrid.value?.focus()
}
const cellClickEvent = ({ row }: any) => {
const $pulldown = xDown.value
demo.value = row.name
$pulldown?.hidePanel()
xGrid.value?.clearCurrentRow()
xGrid.value?.blur()
}
const keydownEvent1 = (e:any) =>{
const $pulldown = xDown.value
if(e.$event.keyCode === 13){
const row = xGrid.value?.getCurrentRecord()
demo.value = row.name
$pulldown?.hidePanel()
xGrid.value?.clearCurrentRow()
xGrid.value?.blur()
}
}
</script>
<style lang="scss" scoped>
.my-dropdown {
width: 600px;
height: 300px;
background-color: #fff;
box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
}
</style>