refactor: refactor ele desc comp

This commit is contained in:
xingyu4j
2025-10-21 15:16:32 +08:00
parent 94628d0c56
commit 18ef9031ca
3 changed files with 211 additions and 144 deletions

View File

@@ -1,79 +1,170 @@
<script lang="tsx"> <script lang="tsx">
import type { DescriptionProps } from 'element-plus'; import type { CSSProperties, PropType, Slots } from 'vue';
import type { PropType } from 'vue'; import type { DescriptionItemSchema, DescriptionProps } from './typing';
import type { DescriptionItemSchema, DescriptionsOptions } from './typing'; import { computed, defineComponent, ref, unref, useAttrs } from 'vue';
import { defineComponent } from 'vue'; import { get, getNestedValue, isFunction } from '@vben/utils';
import { get } from '@vben/utils';
import { ElDescriptions, ElDescriptionsItem } from 'element-plus'; import { ElDescriptions, ElDescriptionsItem } from 'element-plus';
/** 对 Descriptions 进行二次封装 */ const props = {
const Description = defineComponent({ bordered: { default: true, type: Boolean },
name: 'Descriptions', column: {
props: { default: () => {
data: { return { lg: 3, md: 3, sm: 2, xl: 3, xs: 1, xxl: 4 };
type: Object as PropType<Record<string, any>>,
default: () => ({}),
}, },
type: [Number, Object],
},
data: { type: Object },
schema: { schema: {
type: Array as PropType<DescriptionItemSchema[]>,
default: () => [], default: () => [],
type: Array as PropType<DescriptionItemSchema[]>,
}, },
// Descriptions 原生 props size: {
componentProps: { default: 'default',
type: Object as PropType<DescriptionProps>, type: String,
default: () => ({}), validator: (v: string) =>
}, ['default', 'middle', 'small', undefined].includes(v),
}, },
title: { default: '', type: String },
useCard: { default: true, type: Boolean },
};
setup(props: DescriptionsOptions) { function getSlot(slots: Slots, slot: string, data?: any) {
// TODO @puhui999每个 field 的 slot 的考虑 if (!slots || !Reflect.has(slots, slot)) {
// TODO @puhui999from 5.0extra: () => getSlot(slots, 'extra') return null;
/** 过滤掉不需要展示的 */
const shouldShowItem = (item: DescriptionItemSchema) => {
if (item.hidden === undefined) return true;
return typeof item.hidden === 'function'
? !item.hidden(props.data)
: !item.hidden;
};
/** 渲染内容 */
const renderContent = (item: DescriptionItemSchema) => {
if (item.content) {
return typeof item.content === 'function'
? item.content(props.data)
: item.content;
} }
return item.field ? get(props.data, item.field) : null; if (!isFunction(slots[slot])) {
}; console.error(`${slot} is not a function!`);
return null;
}
const slotFn = slots[slot];
if (!slotFn) return null;
return slotFn({ data });
}
return () => ( export default defineComponent({
<ElDescriptions name: 'Description',
{...props} props,
border={props.componentProps?.border} setup(props, { slots }) {
column={props.componentProps?.column} const propsRef = ref<null | Partial<DescriptionProps>>(null);
direction={props.componentProps?.direction}
extra={props.componentProps?.extra} const prefixCls = 'description';
size={props.componentProps?.size} const attrs = useAttrs();
title={props.componentProps?.title}
> const getMergeProps = computed(() => {
{props.schema?.filter(shouldShowItem).map((item) => ( return {
<ElDescriptionsItem ...props,
key={item.field || String(item.label)} ...(unref(propsRef) as any),
label={item.label as string} } as DescriptionProps;
span={item.span} });
>
{renderContent(item)} const getProps = computed(() => {
const opt = {
...unref(getMergeProps),
};
return opt as DescriptionProps;
});
const getDescriptionsProps = computed(() => {
return { ...unref(attrs), ...unref(getProps) } as DescriptionProps;
});
// 防止换行
function renderLabel({
label,
labelMinWidth,
labelStyle,
}: DescriptionItemSchema) {
if (!labelStyle && !labelMinWidth) {
return label;
}
const labelStyles: CSSProperties = {
...labelStyle,
minWidth: `${labelMinWidth}px `,
};
return <div style={labelStyles}>{label}</div>;
}
function renderItem() {
const { data, schema } = unref(getProps);
return unref(schema)
.map((item) => {
const { contentMinWidth, field, render, show, span } = item;
if (show && isFunction(show) && !show(data)) {
return null;
}
function getContent() {
const _data = unref(getProps)?.data;
if (!_data) {
return null;
}
const getField = field.includes('.')
? (getNestedValue(_data, field) ?? get(_data, field))
: get(_data, field);
// if (
// getField &&
// !Object.prototype.hasOwnProperty.call(toRefs(_data), field)
// ) {
// return isFunction(render) ? render('', _data) : (getField ?? '');
// }
return isFunction(render)
? render(getField, _data)
: (getField ?? '');
}
const width = contentMinWidth;
return (
<ElDescriptionsItem key={field} span={span}>
{{
label: () => {
return renderLabel(item);
},
default: () => {
if (item.slot) {
const slotContent = getSlot(slots, item.slot, data);
return slotContent;
}
if (!contentMinWidth) {
return getContent();
}
const style: CSSProperties = {
minWidth: `${width}px`,
};
return <div style={style}>{getContent()}</div>;
},
}}
</ElDescriptionsItem> </ElDescriptionsItem>
))} );
})
.filter((item) => !!item);
}
function renderDesc() {
const extraSlot = getSlot(slots, 'extra');
const slotsObj: any = {
default: () => renderItem(),
};
if (extraSlot) {
slotsObj.extra = () => extraSlot;
}
return (
<ElDescriptions
class={`${prefixCls}`}
title={unref(getMergeProps).title}
{...(unref(getDescriptionsProps) as any)}
>
{slotsObj}
</ElDescriptions> </ElDescriptions>
); );
}
return () => renderDesc();
}, },
}); });
// TODO @puhui999from 5.0emits: ['register'] 事件
export default Description;
</script> </script>

View File

@@ -1,27 +1,43 @@
import type { DescriptionProps } from 'element-plus'; import type { DescriptionProps as ElDescriptionProps } from 'element-plus';
import type { JSX } from 'vue/jsx-runtime';
import type { CSSProperties, VNode } from 'vue'; import type { CSSProperties, VNode } from 'vue';
// TODO @puhui999【content】这个纠结下1vben2.0 是 renderhttps://doc.vvbin.cn/components/desc.html#usage 2 import type { Recordable } from '@vben/types';
// TODO @puhui999vben2.0 还有 sapn【done】、labelMinWidth、contentMinWidth
// TODO @puhui999【hidden】这个纠结下1vben2.0 是 show
export interface DescriptionItemSchema { export interface DescriptionItemSchema {
label: string | VNode; // 内容的描述 labelMinWidth?: number;
field?: string; // 对应 data 中的字段名 contentMinWidth?: number;
content?: ((data: any) => string | VNode) | string | VNode; // 自定义需要展示的内容,比如说 dict-tag // 自定义标签样式
span?: number; // 包含列的数量 labelStyle?: CSSProperties;
labelStyle?: CSSProperties; // 自定义标签样式 // 对应 data 中的字段名
contentStyle?: CSSProperties; // 自定义内容样式 field: string;
hidden?: ((data: any) => boolean) | boolean; // 是否显示 // 内容的描述
label: JSX.Element | string | VNode;
// 包含列的数量
span?: number;
// 是否显示
show?: (...arg: any) => boolean;
// 插槽名称
slot?: string;
// 自定义需要展示的内容
render?: (
val: any,
data?: Recordable<any>,
) => Element | JSX.Element | number | string | undefined | VNode;
} }
// TODO @puhui999vben2.0 还有 title【done】、bordered【done】d、useCollapse、collapseOptions export interface DescriptionProps extends ElDescriptionProps {
// TODO @puhui999from 5.0bordered 默认为 true // 是否包含卡片组件
// TODO @puhui999from 5.0column 默认为 lg: 3, md: 3, sm: 2, xl: 3, xs: 1, xxl: 4 useCard?: boolean;
// TODO @puhui999from 5.0size 默认为 small有 'default', 'middle', 'small', undefined // 描述项配置
// TODO @puhui999from 5.0useCollapse 默认为 true schema: DescriptionItemSchema[];
export interface DescriptionsOptions { // 数据
data?: Record<string, any>; // 数据 data: Recordable<any>;
schema?: DescriptionItemSchema[]; // 描述项配置 // 是否包含边框
componentProps?: DescriptionProps; // antd Descriptions 组件参数 bordered?: boolean;
}
export interface DescInstance {
setDescProps(descProps: Partial<DescriptionProps>): void;
} }

View File

@@ -1,71 +1,31 @@
import type { DescriptionsOptions } from './typing'; import type { Component } from 'vue';
import { defineComponent, h, isReactive, reactive, watch } from 'vue'; import type { DescInstance, DescriptionProps } from './typing';
import { h, reactive } from 'vue';
import Description from './description.vue'; import Description from './description.vue';
/** 描述列表 api 定义 */ export function useDescription(options?: Partial<DescriptionProps>) {
class DescriptionApi { const propsState = reactive<Partial<DescriptionProps>>(options || {});
private state = reactive<Record<string, any>>({});
constructor(options: DescriptionsOptions) { const api: DescInstance = {
this.state = { ...options }; setDescProps: (descProps: Partial<DescriptionProps>): void => {
} Object.assign(propsState, descProps);
},
};
getState(): DescriptionsOptions { // 创建一个包装组件,将 propsState 合并到 props 中
return this.state as DescriptionsOptions; const DescriptionWrapper: Component = {
}
// TODO @puhui999【setState】纠结下1vben2.0 是 data https://doc.vvbin.cn/components/desc.html#usage
setState(newState: Partial<DescriptionsOptions>) {
this.state = { ...this.state, ...newState };
}
}
export type ExtendedDescriptionApi = DescriptionApi;
export function useDescription(options: DescriptionsOptions) {
const IS_REACTIVE = isReactive(options);
const api = new DescriptionApi(options);
// 扩展API
const extendedApi: ExtendedDescriptionApi = api as never;
const Desc = defineComponent({
name: 'UseDescription', name: 'UseDescription',
inheritAttrs: false, inheritAttrs: false,
setup(_, { attrs, slots }) { setup(_props, { attrs, slots }) {
// 合并props和attrs到state return () => {
api.setState({ ...attrs }); // @ts-ignore - 避免类型实例化过深
return h(Description, { ...propsState, ...attrs }, slots);
return () => };
h(
Description,
{
...api.getState(),
...attrs,
}, },
slots, };
);
},
});
// 响应式支持 return [DescriptionWrapper, api] as const;
if (IS_REACTIVE) {
watch(
() => options.schema,
(newSchema) => {
api.setState({ schema: newSchema });
},
{ immediate: true, deep: true },
);
watch(
() => options.data,
(newData) => {
api.setState({ data: newData });
},
{ immediate: true, deep: true },
);
}
return [Desc, extendedApi] as const;
} }