import { ref, watch, unref, type Ref } from 'vue' import type { ProTableProps, TableActionType } from './types' export type UseProTableReturn = [ (instance: TableActionType) => void, TableActionType ] /** 支持 ref/computed 的 props */ export type UseProTablePropsReactive = ProTableProps | Ref /** * 用于 ProTable 的 useProTable,支持通过 ref 调用表格方法 * @param props ProTable 的 props 配置,传入后会通过 setProps 同步到表格(支持 ref/computed 响应式更新) */ export function useProTable(props?: UseProTablePropsReactive): UseProTableReturn { const tableActionRef = ref(null) const getTableProps = (): ProTableProps | undefined => (props ? unref(props as Ref) : undefined) as ProTableProps | undefined const getTableAction = (): TableActionType => { const action = unref(tableActionRef) if (!action) { throw new Error('ProTable instance has not been registered') } return action } const register = (instance: TableActionType) => { tableActionRef.value = instance const tableProps = getTableProps() if (tableProps && Object.keys(tableProps).length > 0) { instance.setProps(tableProps) } } if (props) { watch( () => getTableProps(), (tableProps) => { if (tableProps && tableActionRef.value) { tableActionRef.value.setProps(tableProps) } }, { deep: true } ) } const tableActions: UseProTableReturn[1] = { setProps: (p) => getTableAction().setProps(p), reload: (opt) => getTableAction().reload(opt), redoHeight: () => getTableAction().redoHeight(), setLoading: (v) => getTableAction().setLoading(v), getDataSource: () => getTableAction().getDataSource(), getRawDataSource: () => getTableAction().getRawDataSource(), setTableData: (data) => getTableAction().setTableData(data), getColumns: () => getTableAction().getColumns(), setColumns: (cols) => getTableAction().setColumns(cols), setPagination: (info) => getTableAction().setPagination(info), getSelectRowKeys: () => getTableAction().getSelectRowKeys(), getSelectRows: () => getTableAction().getSelectRows(), clearSelectedRowKeys: () => getTableAction().clearSelectedRowKeys(), setSelectedRowKeys: (keys) => getTableAction().setSelectedRowKeys(keys), deleteSelectRowByKey: (key) => getTableAction().deleteSelectRowByKey(key), updateTableData: (index, key, value) => getTableAction().updateTableData(index, key, value), updateTableDataRecord: (rowKey, record) => getTableAction().updateTableDataRecord(rowKey, record), deleteTableDataRecord: (rowKey) => getTableAction().deleteTableDataRecord(rowKey), insertTableDataRecord: (record, index) => getTableAction().insertTableDataRecord(record, index), getPaginationRef: () => getTableAction().getPaginationRef(), getShowPagination: () => getTableAction().getShowPagination(), setShowPagination: (show) => getTableAction().setShowPagination(show), getRowSelection: () => getTableAction().getRowSelection(), expandAll: () => getTableAction().expandAll?.(), collapseAll: () => getTableAction().collapseAll?.(), scrollToColumn: (column) => getTableAction().scrollToColumn(column) } return [register, tableActions] }