refactor: antdv desc comp
This commit is contained in:
@@ -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';
|
||||
|
||||
/** 描述列表 api 定义 */
|
||||
class DescriptionApi {
|
||||
private state = reactive<Record<string, any>>({});
|
||||
export function useDescription(options?: Partial<DescriptionProps>) {
|
||||
const propsState = reactive<Partial<DescriptionProps>>(options || {});
|
||||
|
||||
constructor(options: DescriptionsOptions) {
|
||||
this.state = { ...options };
|
||||
}
|
||||
const api: DescInstance = {
|
||||
setDescProps: (descProps: Partial<DescriptionProps>): void => {
|
||||
Object.assign(propsState, descProps);
|
||||
},
|
||||
};
|
||||
|
||||
getState(): DescriptionsOptions {
|
||||
return this.state as DescriptionsOptions;
|
||||
}
|
||||
|
||||
// TODO @xingyu:【setState】纠结下:1)vben2.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({
|
||||
// 创建一个包装组件,将 propsState 合并到 props 中
|
||||
const DescriptionWrapper: Component = {
|
||||
name: 'UseDescription',
|
||||
inheritAttrs: false,
|
||||
setup(_, { attrs, slots }) {
|
||||
// 合并props和attrs到state
|
||||
api.setState({ ...attrs });
|
||||
|
||||
return () =>
|
||||
h(
|
||||
Description,
|
||||
{
|
||||
...api.getState(),
|
||||
...attrs,
|
||||
},
|
||||
slots,
|
||||
);
|
||||
setup(_props, { attrs, slots }) {
|
||||
return () => {
|
||||
// @ts-ignore - 避免类型实例化过深
|
||||
return h(Description, { ...propsState, ...attrs }, slots);
|
||||
};
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
// 响应式支持
|
||||
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;
|
||||
return [DescriptionWrapper, api] as const;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user