前言
vben-admin 中 BasicTable
组件开启搜索区域,搜索项可以直接配置的情况外,遇到了需要特殊处理的情况,这时候选择使用插槽。
代码实现
在index.data.ts
文件中配置搜索条件(此处slot配置为status)
export const searchFormSchema: FormSchema[] = [
{
field: 'status',
label: '状态',
slot: 'status',
}
]
页面中使用时,插槽的命名就为form-status
<BasicTable @register="registerTable">
<template #form-status="{ model, field }">
<a-select v-model:value="model[field]" placeholder="请选择" style="width: 300px" :options="statusOptions" show-search />
</template>
</BasicTable>
原理
在BasicTable
文件中搜索区域对应的是BasicForm
,重点在具名插槽的设置上,这里使用getFormSlotKeys
方法获取插槽集合。
↓ 方法里过滤出命名为form-***
的插槽进行返回。所以在页面使用时,插槽的命名规则就是form-***
。
const getFormSlotKeys: ComputedRef<string[]> = computed(() => {
const keys = Object.keys(slots);
return keys
.map((item) => (item.startsWith('form-') ? item : null))
.filter((item) => !!item) as string[];
});
↓ replaceFormSlotKey
方法里,将传递进来的值中form-
处理掉后返回。
function replaceFormSlotKey(key: string) {
if (!key) return '';
return key?.replace?.(/form-/, '') ?? '';
}
因为具名插槽BasicForm
传递过来,所以命名要与其对应起来。也就是说使用时form-
后面的值,与配置时slot的值是相同的
总结
BasicTable
中搜索区域的插槽使用form-***
的命名规则。
为什么这样规定,个人猜测是使其与BasicTable
中其他插槽名称进行区分,防止名称重复,出现不可预估的bug。