feat: 添加设备选择表格组件及页面集成

- 新增设备选择组件,支持设备多选与单选
- 在 demo/test/detail.vue 页面集成设备选择功能
- 修复设备列表页面设备 KEY 显示字段错误问题
This commit is contained in:
fhysy 2025-10-09 16:51:23 +08:00
parent 74717f723b
commit ec29e6d110
3 changed files with 362 additions and 2 deletions

View File

@ -0,0 +1,281 @@
<script setup lang="ts" name="DeviceSelectTable">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { computed, nextTick, onMounted, watch } from 'vue';
import { Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deviceList } from '#/api/device/device';
import { productList } from '#/api/device/product';
import { deviceStateOptions, deviceTypeOptions } from '#/constants/dicts';
interface DeviceVO {
id: number | string;
deviceKey?: string;
deviceName?: string;
deviceType?: string;
deviceState?: string;
imgId?: number | string;
productId?: number | string;
productObj?: { productName?: string };
}
interface Props {
// `id`
modelValue?: DeviceVO[];
// true
multiple?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
modelValue: () => [],
multiple: true,
});
const emit = defineEmits<{
(e: 'update:modelValue', value: DeviceVO[]): void;
(e: 'change', value: DeviceVO[]): void;
}>();
// key 便
const selectedKeySet = computed(
() => new Set((props.modelValue || []).map((r) => r.id)),
);
//
const formOptions: VbenFormProps = {
commonConfig: {
labelWidth: 80,
},
schema: [
{
component: 'Input',
fieldName: 'deviceKey',
label: '设备KEY',
},
{
component: 'Input',
fieldName: 'deviceName',
label: '设备名称',
},
{
component: 'Select',
fieldName: 'productId',
label: '所属产品',
componentProps: {},
},
{
component: 'Select',
fieldName: 'deviceType',
label: '设备类型',
componentProps: {
options: deviceTypeOptions,
},
},
{
component: 'Select',
fieldName: 'deviceState',
label: '设备状态',
componentProps: {
options: deviceStateOptions,
},
},
],
wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};
const columns: VxeGridProps['columns'] = [
// props.multiple
{ type: 'checkbox', width: 60 },
{ title: '设备KEY', field: 'deviceKey' },
{ title: '设备名称', field: 'deviceName' },
{ title: '所属产品', field: 'productObj.productName' },
{
title: '设备类型',
field: 'deviceType',
slots: { default: 'deviceType' },
},
{
title: '设备状态',
field: 'deviceState',
slots: { default: 'deviceState' },
},
];
//
columns[0] = props.multiple
? { type: 'checkbox', width: 60 }
: { type: 'radio', width: 60 };
const gridOptions: VxeGridProps = {
columns,
minHeight: 300,
height: 660,
keepSource: true,
pagerConfig: {
pageSize: 10,
pageSizes: [10, 20, 50, 100],
},
rowConfig: {
keyField: 'id',
},
checkboxConfig: props.multiple
? { highlight: true, reserve: true, trigger: 'row' }
: {},
radioConfig: props.multiple ? {} : { highlight: true, trigger: 'row' },
proxyConfig: {
ajax: {
//
query: async ({ page }, formValues = {}) => {
const params: any = {
pageNum: page.currentPage,
pageSize: page.pageSize,
orderByColumn: 'createTime',
isAsc: 'desc',
...formValues,
};
return await deviceList(params as any);
},
},
},
};
const [BasicTable, tableApi] = useVbenVxeGrid({
formOptions,
gridOptions,
gridEvents: {
//
checkboxChange() {
if (!props.multiple) return;
const curr = tableApi.grid.getCheckboxRecords();
const reserve = tableApi.grid.getCheckboxReserveRecords();
const all = [...curr, ...reserve];
emit('update:modelValue', all as DeviceVO[]);
emit('change', all as DeviceVO[]);
},
//
checkboxAll() {
if (!props.multiple) return;
const curr = tableApi.grid.getCheckboxRecords();
const reserve = tableApi.grid.getCheckboxReserveRecords();
const all = [...curr, ...reserve];
emit('update:modelValue', all as DeviceVO[]);
emit('change', all as DeviceVO[]);
},
//
radioChange() {
if (props.multiple) return;
const record = tableApi.grid.getRadioRecord();
const list = record ? [record] : [];
emit('update:modelValue', list as DeviceVO[]);
emit('change', list as DeviceVO[]);
},
//
pageChange() {
nextTick(() => {
setTimeout(() => {
applySelectionToCurrentPage();
}, 100);
});
},
//
formSubmit() {
nextTick(() => {
setTimeout(() => {
applySelectionToCurrentPage();
}, 100);
});
},
},
});
async function applySelectionToCurrentPage() {
await nextTick();
const pageRows = tableApi.grid.getData();
if (!pageRows || pageRows.length === 0) return;
if (props.multiple) {
await tableApi.grid.clearCheckboxRow();
const needCheck = pageRows.filter((r: any) =>
selectedKeySet.value.has(r.id),
);
if (needCheck.length > 0)
await tableApi.grid.setCheckboxRow(needCheck, true);
} else {
await tableApi.grid.clearRadioRow();
const target = pageRows.find((r: any) => selectedKeySet.value.has(r.id));
if (target) await tableApi.grid.setRadioRow(target);
}
}
//
const loadFormOptions = async () => {
try {
const res = await productList({ pageNum: 1, pageSize: 1000 } as any);
const options = (res?.rows || []).map((item: any) => ({
label: item.productName,
value: item.id,
}));
const placeholder = options.length > 0 ? '请选择' : '暂无产品';
tableApi.formApi.updateSchema([
{
componentProps: { options, placeholder },
fieldName: 'productId',
},
]);
} catch (error) {
console.error('加载表单选项失败:', error);
}
};
//
watch(
() => props.modelValue,
async () => {
await nextTick();
setTimeout(() => {
applySelectionToCurrentPage();
}, 50);
},
{ deep: true },
);
onMounted(async () => {
await loadFormOptions();
setTimeout(() => {
applySelectionToCurrentPage();
}, 200);
});
</script>
<template>
<BasicTable>
<template #toolbar-actions>
<span class="pl-[7px] text-[16px]">设备选择</span>
</template>
<template #deviceType="{ row }">
<Tag color="processing">
{{
deviceTypeOptions.find((option) => option.value === row.deviceType)
?.label
}}
</Tag>
</template>
<template #deviceState="{ row }">
<Tag
:color="
deviceStateOptions.find((o) => o.value === row.deviceState)?.type ||
'default'
"
>
{{
deviceStateOptions.find((o) => o.value === row.deviceState)?.label ||
'-'
}}
</Tag>
</template>
</BasicTable>
</template>

View File

@ -6,6 +6,13 @@ import { defineAsyncComponent, ref } from 'vue';
import { Modal } from 'ant-design-vue';
import 'shiyzhangcron/dist/style.css';
// v-model
type DeviceLite = {
deviceKey?: string;
deviceName?: string;
id: number | string;
productObj?: { productName?: string };
};
const CronPickerModal = defineAsyncComponent(
() => import('../../../components/CronPickerModal/index.vue'),
@ -14,15 +21,22 @@ const CronPickerModal = defineAsyncComponent(
const ProductSelectTable = defineAsyncComponent(
() => import('../../../components/product-select/product-select-table.vue'),
);
const DeviceSelectTable = defineAsyncComponent(
() => import('../../../components/device-select/device-select-table.vue'),
);
const easyCronInnerValue = ref('* * * * * ? *');
const cronModalVisible = ref(false);
const productSelectModalVisible = ref(false);
const deviceSelectModalVisible = ref(false);
//
const selectedProducts = ref<ProductVO[]>([]);
const isMultiple = ref(false);
//
const selectedDevices = ref<DeviceLite[]>([]);
const openCronModal = () => {
cronModalVisible.value = true;
};
@ -54,6 +68,10 @@ const openProductSelectModal = () => {
productSelectModalVisible.value = true;
};
const openDeviceSelectModal = () => {
deviceSelectModalVisible.value = true;
};
const okProductSelectModal = () => {
if (selectedProducts.value.length === 0) {
Modal.error({
@ -65,9 +83,24 @@ const okProductSelectModal = () => {
}
};
const okDeviceSelectModal = () => {
if (selectedDevices.value.length === 0) {
Modal.error({
title: '请选择设备',
});
} else {
console.log('已选择的设备:', selectedDevices.value);
deviceSelectModalVisible.value = false;
}
};
const closeProductSelectModal = () => {
productSelectModalVisible.value = false;
};
const closeDeviceSelectModal = () => {
deviceSelectModalVisible.value = false;
};
</script>
<template>
@ -97,7 +130,7 @@ const closeProductSelectModal = () => {
<!-- 产品选择区域 -->
<div class="mb-8">
<div class="mb-4 flex items-center justify-between">
<h2 class="text-lg font-semibold">产品选择</h2>
<h2 class="text-lg font-semibold">产品/设备选择</h2>
<div class="flex items-center gap-2">
<button
class="rounded bg-green-600 px-3 py-1 text-white"
@ -146,6 +179,38 @@ const closeProductSelectModal = () => {
</button>
</div>
<div class="mb-4 rounded border border-gray-200 p-4">
<h3 class="mb-2 font-medium">
已选择的设备 ({{ selectedDevices.length }} ):
</h3>
<div v-if="selectedDevices.length === 0" class="text-gray-500">
暂无选择的设备
</div>
<div v-else class="space-y-2">
<div
v-for="device in selectedDevices"
:key="device.id"
class="flex items-center justify-between rounded bg-gray-50 p-2"
>
<div>
<span class="font-medium">{{ device.deviceName || '-' }}</span>
<span class="ml-2 text-sm text-gray-500">
({{ device.deviceKey || '-' }})
</span>
</div>
<div class="text-sm text-gray-500">
{{ device.productObj?.productName || '-' }}
</div>
</div>
</div>
<button
class="mt-2 w-full rounded bg-blue-600 px-3 py-1 text-white"
@click="openDeviceSelectModal"
>
选择设备
</button>
</div>
<!-- 产品选择表格 -->
<Modal
title="产品选择"
@ -163,6 +228,20 @@ const closeProductSelectModal = () => {
/>
</div>
</Modal>
<!-- 设备选择表格默认多选 -->
<Modal
title="设备选择"
:open="deviceSelectModalVisible"
:width="1100"
destroy-on-close
@ok="okDeviceSelectModal"
@cancel="closeDeviceSelectModal"
>
<div>
<DeviceSelectTable v-model="selectedDevices" :multiple="true" />
</div>
</Modal>
</div>
<CronPickerModal

View File

@ -475,7 +475,7 @@ const [DeviceDrawer, drawerApi] = useVbenDrawer({
:tooltip-when-ellipsis="true"
class="ml-1 min-w-0 flex-1 !cursor-pointer text-xs text-[#999]"
>
{{ item.productObj?.productKey || '-' }}
{{ item.deviceKey || '-' }}
</EllipsisText>
</div>
<div class="flex">