前端表格复制

我们可能会遇到表格复制的需求,也就是表格填写的时候,不是增加一行数据,而是增加一个表格。
前端表格复制
以下是代码实现和原理分析。

代码实现

boot 工程的 main.ts 中加入以下代码

import {
  registerDesignerFieldWidgetCreator,
  selectorDesignerFieldWidgetCreator
} from '@oinone/kunlun-ui-designer-dependencies';

// 注册无代码组件,将表头分组的无代码组件,注册成字段表格组件
registerDesignerFieldWidgetCreator(
  { widget: 'DynamicCreateTable' },
  selectorDesignerFieldWidgetCreator({ widget: TABLE_WIDGET })!
);

DynamicCreateTableWidget 动态添加表格 ts 组件

import {
  FormO2MTableFieldWidget,
  Widget,
  DslDefinition,
  RuntimeView,
  SubmitValue,
  BaseFieldWidget,
  ModelFieldType,
  SPI,
  ViewType,
  ActiveRecord,
  uniqueKeyGenerator
} from '@oinone/kunlun-dependencies';
import { MyMetadataViewWidget } from './MyMetadataViewWidget';
import DynamicCreateTable from './DynamicCreateTable.vue';

@SPI.ClassFactory(
  BaseFieldWidget.Token({
    viewType: ViewType.Form,
    ttype: ModelFieldType.OneToMany,
    widget: 'DynamicCreateTable'
  })
)
export class DynamicCreateTableWidget extends FormO2MTableFieldWidget {
  public myMetadataViewWidget: MyMetadataViewWidget[] = [];

  @Widget.Reactive()
  public myMetadataViewWidgetLength = 0;

  @Widget.Reactive()
  public myMetadataViewWidgetKeys: string[] = [];

  protected props: Record<string, unknown> = {};

  public initialize(props) {
    super.initialize(props);
    this.props = props;
    this.setComponent(DynamicCreateTable);
    return this;
  }

  // region 创建动态表格

  @Widget.Method()
  public async createTableWidget(record: ActiveRecord) {
    const index = this.myMetadataViewWidget.length;
    const handle = uniqueKeyGenerator();
    const slotKey = `MyMetadataViewWidget_${handle}`;
    const widget = this.createWidget(
      new MyMetadataViewWidget(handle),
      slotKey, // 插槽名称
      {
        subIndex: index,
        metadataHandle: this.metadataHandle,
        rootHandle: this.rootHandle,
        automatic: true,
        internal: true,
        inline: true
      }
    );
    this.initDynamicSubview(this.props, widget);
    widget.setData(record);

    this.myMetadataViewWidgetLength++;
    this.myMetadataViewWidgetKeys.push(slotKey);
    this.myMetadataViewWidget.push(widget);
  }

  protected initDynamicSubview(props: Record<string, unknown>, widget: MyMetadataViewWidget) {
    const { currentViewDsl } = this;
    let viewDsl = currentViewDsl;
    if (!viewDsl) {
      viewDsl = this.getViewDsl(props) as DslDefinition | undefined;
      this.currentViewDsl = viewDsl;
    }
    const runtimeSubview = this.generatorRuntimeSubview(props);
    this.initRuntimeContext(widget, runtimeSubview as RuntimeView);
    this.initSubviewAfterProperties(props);
  }

  // mountedProcess 里数据已经回填,根据值动态创建表格
  protected async mountedProcess() {
    await super.mountedProcess();
    if (Array.isArray(this.value) && this.value.length > 0) {
      this.value.forEach((item) => {
        this.createTableWidget(item);
      });
    } else {
      this.createTableWidget({});
    }
  }

  // region 删除动态表格

  @Widget.Method()
  public async deleteTableWidget(index) {
    this.myMetadataViewWidget.splice(index, 1);
    this.myMetadataViewWidgetKeys.splice(index, 1);
    this.myMetadataViewWidgetLength--;
  }

  // region 数据提交

  public async submit(submitValue: SubmitValue) {
    // 拿到所有子表格的数据
    const records = this.myMetadataViewWidget.map((widget) => widget.dataSource?.[0]).filter((record) => !!record);
    const returnValue = {};
    returnValue[this.itemName] = records;
    return returnValue;
  }
}

DynamicCreateTable.vue 动态添加表格 vue 组件

<template>
  <div class="dynamic-create-table" v-bind="basicProps">
    <div class="dynamic-create-table-container">
      <oio-icon icon="oinone-tianjia2" size="24" @click="createTableWidget({})" />
    </div>
    <template v-for="(key, index) in myMetadataViewWidgetKeys" :key="key">
      <div class="dynamic-delete-table-container">
        <oio-icon icon="oinone-shanchu" size="24" @click="deleteTableWidget(index)" />
        <slot :name="key" />
      </div>
    </template>
  </div>
</template>

<script lang="ts">
import { OioIcon, PropRecordHelper } from '@oinone/kunlun-dependencies';
import { computed, defineComponent, PropType } from 'vue';

export default defineComponent({
  name: 'DynamicCreateTable',
  inheritAttrs: false,
  components: { OioIcon },
  props: {
    myMetadataViewWidgetLength: {
      type: Number
    },
    myMetadataViewWidgetKeys: {
      type: Array as PropType<string[]>
    },
    createTableWidget: {
      type: Function,
      default: () => {}
    },
    deleteTableWidget: {
      type: Function,
      default: () => {}
    }
  },
  setup(props, context) {
    const basicProps = computed(() => {
      return PropRecordHelper.collectionBasicProps(context.attrs, [`inline-table`]);
    });

    return {
      basicProps
    };
  }
});
</script>
<style lang="scss">
.dynamic-create-table {
  display: flex;
  flex-direction: column;
  gap: 24px;

  > .dynamic-create-table-container {
    display: flex;
    justify-content: flex-end;

    > .oio-icon {
      cursor: pointer;
    }
  }

  > .dynamic-delete-table-container {
    position: relative;

    > .oio-icon {
      position: absolute;
      z-index: 1;
      right: 0;
      top: -12px;
      cursor: pointer;
    }
  }

  &.inline-table .oio-default-table-view {
    min-height: unset;
  }
}
</style>

MyMetadataViewWidget 数据隔离组件

import { ActiveRecord, ActiveRecords, CallChaining, MetadataViewWidget, Widget } from '@oinone/kunlun-dependencies';

export class MyMetadataViewWidget extends MetadataViewWidget {
  @Widget.Provide()
  public mountedCallChaining: CallChaining | undefined;

  @Widget.Provide()
  @Widget.Reactive()
  public dataSource: ActiveRecord[] = [];

  @Widget.Method()
  @Widget.Provide()
  public reloadDataSource(records: ActiveRecords | undefined) {
    if (Array.isArray(records)) {
      this.dataSource = records;
    } else {
      this.dataSource = [records || {}];
    }
  }

  @Widget.Provide()
  @Widget.Reactive()
  public activeRecords: ActiveRecord[] = [];

  @Widget.Method()
  @Widget.Provide()
  public reloadActiveRecords(records: ActiveRecords | undefined) {
    if (Array.isArray(records)) {
      this.activeRecords = records;
    } else {
      this.activeRecords = [records || {}];
    }
  }

  @Widget.Reactive()
  @Widget.Provide()
  public rootData: ActiveRecord[] | undefined;

  @Widget.Method()
  @Widget.Provide()
  public reloadRootData(records: ActiveRecords | undefined) {
    if (Array.isArray(records)) {
      this.rootData = records;
    } else {
      this.rootData = [records || {}];
    }
  }

  public initialize(props): this {
    this.mountedCallChaining = props.mountedCallChaining;
    this.subIndex = props.subIndex;
    super.initialize(props);
    return this;
  }

  protected mounted() {
    this.mountedCallChaining?.syncCall();
  }

  public getFormData() {
    return this.activeRecords?.[0];
  }

  public setData(data: Record<string, unknown>) {
    if (data) {
      this.reloadDataSource(data);
      this.reloadActiveRecords(data);
      this.reloadRootData(data);
    }
  }

  /**
   * 当前子路径索引
   */
  @Widget.Reactive()
  protected subIndex: string | number | undefined;

  /**
   * 上级路径
   */
  @Widget.Reactive()
  @Widget.Inject('path')
  protected parentPath: string | undefined;

  /**
   * 完整路径
   */
  @Widget.Reactive()
  @Widget.Provide()
  public get path() {
    const { parentPath, subIndex } = this;
    let path = parentPath || '';
    return `${path}.metadata[${subIndex || ''}]`;
  }
}

原理分析

参考 https://doc.oinone.top/frontend/view-api/21426.html

Oinone社区 作者:银时原创文章,如若转载,请注明出处:https://doc.oinone.top/frontend/components/21429.html

访问Oinone官网:https://www.oinone.top获取数式Oinone低代码应用平台体验

(0)
银时的头像银时数式员工
上一篇 15小时前
下一篇 9小时前

相关推荐

  • oio-checkbox 对选框

    API 属性 Checkbox 参数 说明 类型 默认值 版本 autofocus 自动获取焦点 boolean false checked(v-model:checked) 指定当前是否选中 boolean false disabled 失效状态 boolean false indeterminate 设置 indeterminate 状态,只负责样式控制 boolean false value 与 CheckboxGroup 组合使用时的值 boolean | string | number – 事件 事件名称 说明 回调参数 版本 change 变化时回调函数 Function(e:Event) –

    2023年12月18日
    63000
  • 前端自定义组件之左右滑动

    本文将讲解如何通过自定义,实现容器内的左右两个元素,通过左右拖拽分隔线,灵活调整宽度。其中左右元素里的内容都是界面设计器拖出来的。 实现路径 1. 界面设计器拖出页面 我们界面设计器拖个布局容器,然后在左右容器里拖拽任意元素。完成后点击右上角九宫格,选中布局容器,填入组件 api 名称,作用是把布局容器切换成我们自定义的左右滑动组件,这里的 api 名称和自定义组件的 widget 对应。最后发布页面,并绑定菜单。 2. 组件实现 widget 组件重写了布局容器,核心函数 renderLeft、renderRight,通过 DslRender.render 方法渲染界面设计器拖拽的元素。 import { BasePackWidget, DefaultContainersWidget, DslDefinition, DslRender, SPI, Widget } from '@oinone/kunlun-dependencies'; import LeftRightSlide from './LeftRightSlide.vue'; // 拿到界面设计器配置的子容器元素 function fetchContainerChildren(widgets?: DslDefinition[], level = 3): DslDefinition[] { if (!widgets) { return []; } const children: DslDefinition[] = []; for (const widget of widgets) { if (widget.widget === 'container') { children.push(widget); } else if (level >= 1) { fetchContainerChildren(widget.widgets, level – 1).forEach((child) => children.push(child)); } } return children; } @SPI.ClassFactory(BasePackWidget.Token({ widget: 'LeftRightSlide' })) export class LeftRightSlideWidget extends DefaultContainersWidget { public initialize(props) { super.initialize(props); this.setComponent(LeftRightSlide); return this; } // 获取容器的子元素 public get containerChildren(): DslDefinition[] { return fetchContainerChildren(this.template?.widgets); } // 初始宽度配置 @Widget.Reactive() public get initialLeftWidth() { return this.getDsl().initialLeftWidth || 400; } // 最小左宽度配置 @Widget.Reactive() public get minLeftWidth() { return this.getDsl().minLeftWidth || 200; } // 最小右宽度配置 @Widget.Reactive() public get minRightWidth() { return this.getDsl().minRightWidth || 200; } // 根据容器子元素渲染左侧 @Widget.Method() public renderLeft() { // 把容器的第一个元素作为左侧 const containerLeft = this.containerChildren[0]; if (containerLeft) { return DslRender.render(containerLeft); } } // 根据容器子元素渲染右侧 @Widget.Method() public renderRight() { // 把容器的第二个元素作为右侧 const containerRight = this.containerChildren[1]; if…

    2025年7月8日
    34700
  • oio-empty-data 空数据状态

    何时使用 当目前没有数据时,用于显式的用户提示。 初始化场景时的引导创建流程。 API 参数 说明 类型 默认值 版本 description 自定义描述内容 string | v-slot – image 设置显示图片,为 string 时表示自定义图片地址 string | v-slot false imageStyle 图片样式 CSSProperties –

    2023年12月18日
    67900
  • oio-button 按钮

    主按钮:用于主行动点,一个操作区域只能有一个主按钮。 默认按钮:用于没有主次之分的一组行动点。 虚线按钮:常用于添加操作。 文本按钮:用于最次级的行动点。 链接按钮:一般用于链接,即导航至某位置。 以及四种状态属性与上面配合使用。 危险:删除/移动/修改权限等危险操作,一般需要二次确认。 禁用:行动点不可用的时候,一般需要文案解释。 加载中:用于异步操作等待反馈的时候,也可以避免多次提交。 API 按钮的属性说明如下: 属性 说明 类型 默认值 版本 block 将按钮宽度调整为其父宽度的选项 boolean false disabled 按钮失效状态 boolean false icon 设置按钮的图标类型 v-slot – loading 设置按钮载入状态 boolean | { delay: number } false type 设置按钮类型 primary | ghost | dashed | link | text | default default 事件 事件名称 说明 回调参数 版本 click 点击按钮时的回调 (event) => void 支持原生 button 的其他所有属性。

    2023年12月18日
    39400
  • oio-select 选择器

    API Select props 参数 说明 类型 默认值 版本 allowClear 支持清除 boolean false autofocus 默认获取焦点 boolean false clearIcon 自定义的多选框清空图标 VNode | slot – disabled 是否禁用 boolean false dropdownClassName 下拉菜单的 className 属性 string – dropdownRender 自定义下拉框内容 ({menuNode: VNode, props}) => VNode | v-slot – filterOption 是否根据输入项进行筛选。当其为一个函数时,会接收 inputValue option 两个参数,当 option 符合筛选条件时,应返回 true,反之则返回 false。 boolean | function(inputValue, option) true getTriggerContainer 菜单渲染父节点。默认渲染到 body 上,如果你遇到菜单滚动定位问题,试试修改为滚动的区域,并相对其定位。 function(triggerNode) () => document.body menuItemSelectedIcon 自定义当前选中的条目图标 VNode | slot – options options 数据,如果设置则不需要手动构造 selectOption 节点 array<{value, label, [disabled, key, title]}> [] placeholder 选择框默认文字 string|slot – removeIcon 自定义的多选框清除图标 VNode | slot – suffixIcon 自定义的选择框后缀图标 VNode | slot – value(v-model:value) 指定当前选中的条目 string|string[]|number|number[] – 注意,如果发现下拉菜单跟随页面滚动,或者需要在其他弹层中触发 Select,请尝试使用 getPopupContainer={triggerNode => triggerNode.parentNode} 将下拉弹层渲染节点固定在触发器的父元素中。 事件 事件名称 说明 回调参数 blur 失去焦点的时回调 function change 选中 option,或 input 的 value 变化(combobox 模式下)时,调用此函数 function(value, option:Option/Array<Option>) deselect 取消选中时调用,参数为选中项的 value (或 key) 值,仅在 multiple 或 tags 模式下生效 function(value,option:Option) dropdownVisibleChange 展开下拉菜单的回调 function(open) focus 获得焦点时回调 function inputKeyDown 键盘按下时回调 function mouseenter 鼠标移入时回调 function mouseleave 鼠标移出时回调 function popupScroll 下拉列表滚动时的回调 function search 文本框值变化时回调 function(value: string) select 被选中时调用,参数为选中项的 value (或 key) 值 function(value, option:Option)

    2023年12月18日
    37700

Leave a Reply

登录后才能评论