【界面设计器】自定义字段组件实战——表格字段内嵌表格

阅读之前

此文章为实战教程,已假定你熟悉了【界面设计器】较为完整的【自定义组件】相关内容。

如果在阅读过程中出现的部分概念无法理解,请自行学习相关内容。【前端】文章目录

业务背景

表格中的一对多(O2M)多对多(M2M)字段使用表格展开。

演示内容:在【商品】的表格中存在【库存信息】这一列,这一列的内容通过表格展示【尺码】和【数量】两列。

业务分析及实现思路

从需求来看,我们需要实现一个【内嵌表格】组件,并且该组件允许在【表格】视图中使用。与之前不同的是,这里我们需要支持两个业务类型一对多(O2M)多对多(M2M),即一个组件中包含两个元件。

在【内嵌表格】组件的属性面板中,我们需要再定义一个【内嵌表格配置】组件,用来选择内嵌表格中需要哪些字段进行组合,以及为每个组合提供一些基础配置。

这里需要理解一个基本概念,即【内嵌表格】的属性面板是【内嵌表格配置】的【执行页面】。所有组件的属性面板在【执行页面】时都是【表单】视图。

因此我们可以实现一个【内嵌表格配置】组件,并且该组件允许在【表单】视图中使用。其业务类型使用【文本】,我们在保存配置数据时,可以使用JSON数据结构来存储复杂结构。(这里的实现思路并非是最符合协议设定的,但可以满足绝大多数组件场景)

在【内嵌表格配置】组件中,我们可以允许用户添加/移除组合,并且每个组合有两个属性,【标题】和【字段】。

一些解释

看过【界面设计器】自定义字段组件实战——表格字段组合展示文章的读者可能很熟悉这一实现思路,会想当然的尝试将两个组件进行合并。这里我觉得有必要作出一些实现思路上的解释。

虽然在表面上看起来【组合列配置】和【内嵌表格配置】用到的属性完全一样,但在实现上,由于关联关系的查询需要在组件中特殊处理【透出字段(选项字段列表)】字段(【界面设计器】组件开发常见问题
中对该属性进行了解释),才能查询到相应的关联数据。

不仅如此,这两个组件所代表的含义也完全不同。【组合列配置】是在一列中配置需要展示的字段,它在未来可能会增加【颜色(根据条件判断展示不同的颜色)】、【动作(可点击的行为)】等等诸多与之相关的属性。【内嵌表格配置】是在一列中配置表格中的多列,它在未来可能会增加【行高(控制表格行高)】、【支持排序(表格列支持排序)】等等诸多与之相关的属性。

在这里希望读者可以理解一点:相似并不代表相关。组件的抽象与归纳整理的不同点在于,抽象更需要关心其本身所代表的含义,而不是仅关注其相似程度。将多个相似度高但含义不同的组件进行归纳整理得到的只是一个含义不明,无法适应变化的组件。

因此,我们仍然使用两个不同的组件进行实现。

准备工作

此处你应该已经准备好了【商品】和【库存】两个模型,并且可以完整执行【商品】模型的全部【增删改查】操作。

业务模型定义(此处模型定义并非业务中正常使用的模型定义,仅作为演示使用)

(以下仅展示本文章用到的模型字段,忽略其他无关字段。)

关联字段:-左侧表示当前模型中的字段API名称,右侧表示关联模型中的字段API名称。

商品(Item)
名称 API名称 业务类型 是否多值 长度(单值长度) 关联模型 关联字段
ID id 整数 - - -
编码 code 文本 128 - -
名称 name 文本 128 - -
库存信息 inventoryInfo 一对多 - 库存(Inventory) id - itemId
库存(Inventory)
名称 API名称 业务类型 是否多值 长度(单值长度) 关联模型 关联字段
ID id 整数 128 - -
商品 item 多对一 - 商品(Item) itemId - id
商品ID itemId 整数 - - -
尺码 size 文本 128 - -
库存 count 整数 - - -

PS:如果是使用【模型设计器】创建这两个模型,在创建关联关系字段时必须使用双向关联,才能正确建立关联关系。

实现页面效果展示

表格视图

image.png

表单视图

image.png

库存信息配置

image.png

创建组件、元件

准备工作完成后,我们需要根据【业务背景】确定【组件】以及【元件】相关信息,并在【界面设计器】中进行创建。

以下操作过程将省略详细步骤,仅展示可能需要确认的关键页面。

创建内嵌表格组件

image.png

创建内嵌表格元件(一对多)

image.png

创建内嵌表格元件(多对多)

image.png

创建内嵌表格配置组件

image.png

创建内嵌表格配置元件

image.png

设计内嵌表格元件属性面板

(两个元件的属性面板可以完全一致)

创建tableConfig字段,并切换至【内嵌表格配置】组件。

image.png

image.png

再拖入【透出字段(选项字段列表)】,并设置为隐藏。

image.png

设计内嵌表格配置元件属性面板

image.png

启动SDK工程进行组件基本功能开发

开发步骤参考

  • 打开【表格】视图,将【库存信息】字段的组件切换为【内嵌表格】
  • 在属性面板中看到【内嵌表格配置】组件,并优先实现【内嵌表格配置】组件。这里的属性面板就是【内嵌表格配置】组件对应的【执行页面】。
  • 当【内嵌表格配置】组件可以按照预先设计的数据结构正确保存tableConfig属性时,可以在【内嵌表格】组件中的props定义中直接获取该属性,接下来就可以进行【内嵌表格】组件的开发。

代码实现参考

工程结构

image.png

typing.ts
export interface InlineTableConfig {
  key: string;
  label?: string;
  field?: string;
}
FieldService.ts
import { GenericFunctionService, IModelField, QueryPageResult } from '@kunlun/dependencies';

export class FieldService {
  private static readonly FIELD_MODEL = 'base.Field';

  public static async fetchFieldsByModel(model: string, filter?: string): Promise<IModelField[]> {
    let rsql = `model == "${model}"`;
    if (filter) {
      rsql = `${rsql} and ${filter}`;
    }
    const res = await GenericFunctionService.INSTANCE.simpleExecuteByName<QueryPageResult<IModelField>>(
      FieldService.FIELD_MODEL,
      'queryPage',
      {
        size: -1
      },
      {
        rsql
      }
    );
    return res?.content || [];
  }
}
InlineTableConfig.vue
<template>
  <div class="inline-table-config">
    <oio-form v-for="item in list" :data="item" :key="item.key">
      <oio-form-item label="标题" name="label">
        <oio-input v-model:value="item.label" />
      </oio-form-item>
      <oio-form-item label="字段" name="field">
        <a-select
          class="oio-select"
          dropdownClassName="oio-select-dropdown"
          v-model:value="item.field"
          :options="fields"
        />
      </oio-form-item>
      <oio-button type="link" @click="() => removeItem(item)">移除</oio-button>
    </oio-form>
    <oio-button type="primary" block @click="addItem">添加</oio-button>
  </div>
</template>
<script lang="ts">
import { uniqueKeyGenerator } from '@kunlun/dependencies';
import { OioButton, OioForm, OioFormItem, OioInput } from '@kunlun/vue-ui-antd';
import { Select as ASelect } from 'ant-design-vue';
import { defineComponent, onMounted, PropType, ref, watch } from 'vue';
import { InlineTableConfig } from '../../typing';
import { FieldService } from './service/FieldService';

interface SelectItem {
  label: string;
  value: string;
}

export default defineComponent({
  name: 'InlineTableConfig',
  components: {
    OioForm,
    OioFormItem,
    OioInput,
    OioButton,
    ASelect
  },
  props: {
    referenceModel: {
      type: String
    },
    value: {
      type: String
    },
    change: {
      type: Function
    },
    setOptionFields: {
      type: Function as PropType<(optionFields: string[]) => void>
    }
  },
  setup(props) {
    const list = ref<InlineTableConfig[]>([]);
    if (props.value) {
      list.value = JSON.parse(props.value);
    }

    const addItem = () => {
      list.value = [...list.value, { key: uniqueKeyGenerator() }];
    };

    const removeItem = (item: InlineTableConfig) => {
      const { key } = item;
      if (!key) {
        return;
      }
      const index = list.value.findIndex((v) => v.key === key);
      if (index >= 0) {
        list.value.splice(index, 1);
      }
    };

    const fields = ref<SelectItem[]>([]);

    onMounted(() => {
      if (props.referenceModel) {
        FieldService.fetchFieldsByModel(props.referenceModel, 'ttype =out= (O2O, O2M, M2O, M2M)').then((res) => {
          fields.value = res.map((v) => ({
            label: v.displayName || v.field!,
            value: v.field!
          }));
        });
      }
    });

    watch(
      list,
      (val) => {
        if (props.referenceModel) {
          props.setOptionFields?.(val.filter((v) => !!v.field).map((v) => v.field) as string[]);
        }
        props.change?.(JSON.stringify(val));
      },
      { deep: true }
    );

    return {
      list,
      addItem,
      removeItem,
      fields
    };
  }
});
</script>
FormStringInlineTableConfigFieldWidget.ts
import { FormFieldWidget, ModelFieldType, SPI, ViewType, Widget } from '@kunlun/dependencies';
import InlineTableConfig from './InlineTableConfig.vue';

interface InternalMetadata {
  modelReferences?: {
    model?: string;
  };
}

@SPI.ClassFactory(
  FormFieldWidget.Token({
    viewType: ViewType.Form,
    ttype: ModelFieldType.String,
    widget: 'InlineTableConfig',
    multi: false
  })
)
export class FormStringInlineTableConfigFieldWidget extends FormFieldWidget {
  public initialize(props) {
    super.initialize(props);
    this.setComponent(InlineTableConfig);
    return this;
  }

  @Widget.Reactive()
  protected get referenceModel(): string | undefined {
    return (this.formData._metadata as InternalMetadata)?.modelReferences?.model;
  }

  @Widget.Method()
  public setOptionFields(optionFields: string[]) {
    this.formData.optionFields = optionFields;
  }
}
InlineTable.vue(需新增文件)
<template>
  <a-table
    class="column-inline-table"
    :data-source="dataSource"
    :columns="columns"
    :pagination="false"
    size="small"
    :scroll="{ y: 140 }"
  />
</template>
<script lang="ts">
import { ActiveRecord } from '@kunlun/dependencies';
import { Table as ATable } from 'ant-design-vue';
import { computed, defineComponent, PropType } from 'vue';
import { InlineTableConfig } from '../../typing';

export default defineComponent({
  name: 'InlineTable',
  inheritAttrs: false,
  components: {
    ATable
  },
  props: {
    dataSource: {
      type: Array as PropType<ActiveRecord[]>
    },
    fields: {
      type: Array as PropType<InlineTableConfig[]>
    }
  },
  setup(props) {
    const dataSource = computed(() => props.dataSource || []);

    const columns = computed(() =>
      (props.fields || []).map((v) => ({
        key: v.key,
        title: v.label,
        dataIndex: v.field
      }))
    );

    return {
      dataSource,
      columns
    };
  }
});
</script>
<style lang="scss">
.column-inline-table.ant-table-wrapper {
  height: 100%;
}
</style>

PS:此处由于平台使用了inline-table的class名称,为了避免冲突,使用column-inline-table

AbstractInlineTableFieldWidget.ts
import { RowContext, TableListFieldWidget, Widget } from '@kunlun/dependencies';
import { createVNode, VNode } from 'vue';
import { InlineTableConfig } from '../../typing';
import InlineTable from './InlineTable.vue';

export class AbstractInlineTableFieldWidget extends TableListFieldWidget {
  @Widget.Reactive()
  protected get tableConfig(): InlineTableConfig[] {
    const { tableConfig } = this.getDsl();
    if (tableConfig) {
      return JSON.parse(tableConfig);
    }
    return [];
  }

  protected getFields() {
    return this.tableConfig.filter((v) => !!v.field);
  }

  @Widget.Method()
  public renderDefaultSlot(context: RowContext): VNode[] | string {
    return [
      createVNode(InlineTable, {
        dataSource: this.compute(context),
        fields: this.getFields()
      })
    ];
  }
}
TableO2mMultiInlineTableFieldWidget.ts
import { BaseFieldWidget, ModelFieldType, SPI, ViewType } from '@kunlun/dependencies';
import { AbstractInlineTableFieldWidget } from './AbstractInlineTableFieldWidget';

@SPI.ClassFactory(
  BaseFieldWidget.Token({
    viewType: ViewType.Table,
    ttype: ModelFieldType.OneToMany,
    widget: 'InlineTable',
    multi: true
  })
)
export class TableO2mMultiInlineTableFieldWidget extends AbstractInlineTableFieldWidget {}
TableM2mMultiInlineTableFieldWidget.ts
import { BaseFieldWidget, ModelFieldType, SPI, ViewType } from '@kunlun/dependencies';
import { AbstractInlineTableFieldWidget } from './AbstractInlineTableFieldWidget';

@SPI.ClassFactory(
  BaseFieldWidget.Token({
    viewType: ViewType.Table,
    ttype: ModelFieldType.ManyToMany,
    widget: 'InlineTable',
    multi: true
  })
)
export class TableM2mMultiInlineTableFieldWidget extends AbstractInlineTableFieldWidget {}

实现效果展示

配置内嵌表格

image.png

表格展示

image.png

内嵌表格属性面板

image.png

Oinone社区 作者:数式-海波原创文章,如若转载,请注明出处:https://doc.oinone.top/frontend/59.html

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

(0)
数式-海波的头像数式-海波数式管理员
上一篇 2023年6月20日 pm4:07
下一篇 2023年11月2日 pm1:58

相关推荐

  • 前端 SPI 注册 + 渲染

    在阅读本篇文章之前,您需要学习以下知识点: 1: TS 结合 Vue 实现动态注册和响应式管理 前端开发者在使用 oinone 平台的时候会发现,不管是自定义字段还是视图,对应的 typescript 都会用到@SPI.ClassFactory(参数),然后在对用的class中重写initialize方法`: @SPI.ClassFactory(参数) export class CustomClass extends xxx { public initialize(props) { super.initialize(props); this.setComponent(FormString); return this; } } 本文将带您熟悉 oinone 前端的 SPI 注册机制以及 TS + Vue 的渲染过程。 不管是自定义字段还是视图@SPI.ClassFactory(参数)都是固定写法,区别在于参数不同,这篇文章里面详细描述了参数的定义。 SPI 注册机制 有自定义过字段、视图经验的开发者可能会发现,字段(表单字段)SPI 注册用的是FormFieldWidget.Token生成对应的参数,视图 SPI 注册用的是BaseElementWidget.Token,那么为什么要这样定义呢? 大家可以想象成现在有一个大的房子,房子里面有很多房间,每个房间都有自己的名字,比如FormFieldWidget就是房间的名字,BaseElementWidget也是房间的名字,这样一来我们就可以根据不同的房间存放不同的东西。 下面给大家展示下伪代码实现: class SPI { static container = new Map<string, WeakMap<object, object>>() static ClassFactory(token) { return (target) => { if(!SPI.container.get(token.type)) { SPI.container.set(token.type, new WeakMap()) } const services = SPI.container.get(token.type) services?.set(token, target) } } } class FormFieldWidget { static Token(options) { return { …options, type: 'Field' } } static Selector(options) { const fieldWidgets = SPI.container.get('Field') if(fieldWidgets) { return fieldWidgets.get(options)! } return null } } @SPI.ClassFactory(FormFieldWidget.Token({ viewType: 'Form', ttype: 'String', widget: 'Input' })) class StringWidget { } // 字段元数据 const fieldMeta = { name: "name", field: "name", mode: 'demo.model', widget: 'Input', ttype: 'String', viewType: 'Form' } // 找到对应的widget const widget = FormFieldWidget.Selector({ viewType: fieldMeta.viewType, ttype: fieldMeta.ttype, widget: fieldMeta.widget, }) 在上述代码中,我们主要是做了这么写事情: 1.SPI class class SPI { static container = new Map<string, WeakMap<object, object>>() } SPI 类是一个静态类,用于管理服务的注册和获取。 container 是一个静态属性,类型是 Map,它的键是字符串,值是 WeakMap。这个结构允许我们为每个服务类型(例如,Field)管理多个服务实例。 2.ClassFactory 方法 static ClassFactory(token) { return (target) => { if…

    2024年9月26日
    84600
  • 页面出现中文乱码,该怎么解决?

    可能性1: 后端读取视图的xml解析时,由于系统缺少中文字体,导致解析后出现乱码,这种问题常见于采用docker镜像部署的情况,很多基础镜像不带中文字体。 解决方案:在物理系统或者docker镜像内安装中文字体 可能性2: win环境下未指定文件的编码类型 解决方案: 启动命令中加上-Dfile.encoding=UTF-8参数 # 示例命令 java -jar -Dfile.encoding=UTF-8 pamirs-demo-boot-1.0.0-SNAPSHOT.jar -Plifecycle=INSTALL

    2023年11月1日
    63700
  • 如何在自有前端工程中使用gql请求?

    场景 客户在个性化程度比较高的h5工程中想使用平台的服务端能力,这个时候需要调用后端的gql请求,此时需要引入平台的请求库依赖 npm的package.json中加入依赖 此文档以4.x举例,使用其他版本的请自行修改版本号 "dependencies": { "@kunlun/request": "~4.3.0", "@kunlun/state": "~4.3.0" } 使用示例 import { HttpClient } from ‘@kunlun/request’ const http = HttpClient.getInstance() http.setBaseURL(”) export const login = (data) => { const gqlBody = `mutation { pamirsUserTransientMutation { login(user: {login: “${data.username}”, password: “${data.password}”}) { broken errorMsg errorCode errorField } } }` return http.mutate(‘user’, gqlBody) } 注意事项 开发环境记得配置oinone请求的路由转发规则,这里以vite.config.js举例 import { defineConfig } from ‘vite’ export default defineConfig({ server: { port: 8088, open: true, proxy: { ‘/pamirs’: { changeOrigin: true, // 服务端请求地址 target: ‘http://127.0.0.1:8091’ } } } })

    2023年11月1日
    46200
  • 根据固定的接口返回数据动态控制按钮的显隐

    在项目开发中,我们经常会面临这样的情况:当前按钮的显示与隐藏需要根据后端某个接口返回的数据来决定,而无法通过权限配置进行处理。为了解决这个问题,我们可以通过自定义的方式来处理这一功能。 首先,我们需要知道当前动作是什么类型的动作,例如「服务端动作、跳转动作、打开弹窗的动作、打开抽屉的动作」。 ServerActionWidget -> 服务端动作DialogViewActionWidget -> 打开弹窗动作DrawerViewActionWidget -> 打开抽屉动作RouterViewActionWidget -> 路由跳转动作 下面是一个示例代码,演示了如何通过自定义的方式处理按钮的显示与隐藏逻辑。 import { ActionType, ActionWidget, SPI, ServerActionWidget, Widget, http } from '@kunlun/dependencies'; @SPI.ClassFactory( ActionWidget.Token({ actionType: ActionType.Server, model: 'resource.k2.Model0000000100', name: 'create' }) ) export class MyAction extends ServerActionWidget { // 当前动作是服务端动作,继承的是 ServerActionWidget @Widget.Reactive() private needInvisible = false; @Widget.Reactive() public get invisible(): boolean { return this.needInvisible; } protected mounted(): void { super.mounted(); // 模拟接口 http.query(模块名, `graphql`).then(res => { if(res) { this.needInvisible = true } }) } } 在实际应用中,我们可以调用后端接口,根据返回的数据动态修改 needInvisible 这个值,从而实现按钮的动态显示与隐藏效果。这样的设计使得按钮的显示状态更加灵活,并且能够根据后端数据动态调整,提高了系统的可定制性。

    前端 2023年11月23日
    58700
  • 树型表格全量加载数据如何处理

    阅读该文档的前置条件 【界面设计器】树形表格 1.前端自定义表格组件 import { ActiveRecord, BaseElementWidget, Condition, Entity, SPI, TableWidget, ViewType } from '@kunlun/dependencies'; @SPI.ClassFactory( BaseElementWidget.Token({ type: ViewType.Table, widget: ['demo-tree-table'] }) ) export class TreeTableWidget extends TableWidget { // 默认展开所有层级 protected getTreeExpandAll() { return true; } // 关闭懒加载 protected getTreeLazy(): boolean { return false; } public async $$loadTreeNodes(condition?: Condition, currentRow?: ActiveRecord): Promise<Entity[]> { // 树表加载数据的方法,默认首次只查第一层的数据,这里去掉这个查询条件的参数condition,这样就会查所有层级数据 return super.$$loadTreeNodes(undefined, currentRow); } } 2. 注册layout import { registerLayout, ViewType } from '@kunlun/dependencies'; const install = () => { registerLayout( ` <view type="TABLE"> <element widget="actionBar" slot="actionBar" slotSupport="action"> <xslot name="actions" slotSupport="action" /> </element> <element widget="demo-tree-table" slot="table"> <element widget="expandColumn" slot="expandRow" /> <xslot name="fields" slotSupport="field" /> <element widget="rowActions" slot="rowActions" slotSupport="action" /> </element> </view> `, { viewType: ViewType.Table, model: "resource.resourceCity", // 变量,需要替换 actionName: "MenuuiMenu6f6005bdddba468bb2fb814a62fa83c6", // 变量,需要替换 } ); }; install();

    2024年8月17日
    68600

Leave a Reply

登录后才能评论