前端自定义组件之多页面步骤条

本文将讲解如何通过自定义,实现多页面的步骤条组件。其中每个步骤的元素里都对应界面设计器的一个页面。以下是代码实现和原理分析。

代码实现

NextStepWidget 多页面步骤条 ts 组件

import {
  CallChaining,
  createRuntimeContextByView,
  customMutation,
  customQuery,
  RuntimeView,
  SPI,
  ViewCache,
  Widget,
  DefaultTabsWidget,
  BasePackWidget
} from '@oinone/kunlun-dependencies';
import { isEmpty } from 'lodash-es';
import { MyMetadataViewWidget } from './MyMetadataViewWidget';
import NextStep from './NextStep.vue';
import { IStepConfig, StepDirection } from './type';

@SPI.ClassFactory(BasePackWidget.Token({ widget: 'NextStep' }))
export class NextStepWidget extends DefaultTabsWidget {
  public initialize(props) {
    this.titles = props.template?.widgets?.map((item) => item.title) || [];
    props.template && (props.template.widgets = []);
    super.initialize(props);
    this.setComponent(NextStep);
    return this;
  }

  @Widget.Reactive()
  public get invisible() {
    return false;
  }

  // 配置的每一步名称
  @Widget.Reactive()
  public titles = [];

  // region 上一步下一步配置

  // 步骤配置,切换的顺序就是数组的顺序,模型没有限制
  @Widget.Reactive()
  public get stepJsonConfig() {
    let data = JSON.parse(
      this.getDsl().stepJsonConfig ||
        '[{"model":"resource.ResourceCountry","viewName":"国家form"},{"model":"resource.ResourceProvince","viewName":"省form"},{"model":"resource.ResourceCity","viewName":"市form"}]'
    );
    return data as IStepConfig[];
  }

  // 切换上一步下一步
  @Widget.Method()
  public async onStepChange(stepDirection: StepDirection) {
    // 没有激活的,说明是初始化,取第一步
    if (!this.activeStepKey) {
      const step = this.stepJsonConfig[0];
      if (step) {
        this.activeStepKey = `${step.model}_${step.viewName}`;
        await this.initStepView(step);
      }
      return;
    }

    // 获取当前步骤的索引
    if (this.currentActiveKeyIndex > -1) {
      await this.onSave();
      // 获取下一步索引
      const nextStepIndex =
        stepDirection === StepDirection.NEXT ? this.currentActiveKeyIndex + 1 : this.currentActiveKeyIndex - 1;
      // 在索引范围内,则渲染视图
      if (nextStepIndex >= 0 && nextStepIndex < this.stepJsonConfig.length) {
        const nextStep = this.stepJsonConfig[nextStepIndex];
        if (nextStep) {
          this.activeStepKey = `${nextStep.model}_${nextStep.viewName}`;
          await this.initStepView(nextStep);
        }
      }
    }
  }

  // region 创建上一步下一步视图

  // 每个步骤视图组件
  @Widget.Reactive()
  public stepViewWidget: Record<string, MyMetadataViewWidget> = {};

  // 当前激活的步骤,用 model 和 viewName 联合作为 key
  @Widget.Reactive()
  public activeStepKey: string = '';

  // 当前激活的步骤索引,即当前是第几步,从 0 开始
  @Widget.Reactive()
  public get currentActiveKeyIndex() {
    return this.stepJsonConfig.findIndex((step) => `${step.model}_${step.viewName}` === this.activeStepKey);
  }

  // 传入 step,动态创建一个步骤视图,并初始化数据
  public async initStepView(step: IStepConfig) {
    const widget = this.stepViewWidget[`${step.model}_${step.viewName}`];
    if (widget) {
      // 命中缓存
      this.initStepViewData(step);
      return;
    }

    // 根据 stepJsonConfig 里的 model 和 viewName 获取页面配置
    const resView = await ViewCache.get(step.model, step.viewName);
    if (resView) {
      // 创建一个元数据隔离的视图组件
      const widget = this.createDynamicWidget(resView, step);
      if (!widget) {
        throw new Error('Invalid widget.');
      }
      this.stepViewWidget[`${step.model}_${step.viewName}`] = widget;
      this.initStepViewData(step);
    }
  }

  // 根据取的中间协议视图 view,动态构建视图
  public createDynamicWidget(view: RuntimeView, step: IStepConfig) {
    if (view) {
      // 中间协议构建上下文
      const runtimeContext = createRuntimeContextByView(view, true, `Form_${Math.random()}`, this.currentHandle);
      runtimeContext.parentContext = this.rootRuntimeContext;
      // 取得上下文唯一标识

      const runtimeContextHandle = runtimeContext.handle;
      const widget = this.createWidget(
        new MyMetadataViewWidget(runtimeContextHandle),
        `Form_${step.model}_${step.viewName}`,
        {
          metadataHandle: runtimeContextHandle,
          rootHandle: runtimeContextHandle,
          mountedCallChaining: new CallChaining(),
          submitCallChaining: new CallChaining(),
          refreshCallChaining: new CallChaining(),
          dataSource: [{}],
          activeRecords: [{}],
          inline: false
        }
      );
      widget.initContext(runtimeContext);
      return widget;
    }
  }

  // 每个 step 的请求数据逻辑
  private async initStepViewData(step: IStepConfig) {
    // 当前步骤的 widget
    const widget = this.stepViewWidget[`${step.model}_${step.viewName}`];
    if (!widget) {
      return;
    }

    if (this.currentActiveKeyIndex > 0) {
      // 根据上一步的数据,构造数据回填
      const lastWidget =
        this.stepViewWidget[
          `${this.stepJsonConfig[this.currentActiveKeyIndex - 1].model}_${
            this.stepJsonConfig[this.currentActiveKeyIndex - 1].viewName
          }`
        ];
      const lastWidgetData = (await lastWidget.getData()) || {};
      const data = (await customQuery(step.model, 'construct', lastWidgetData)) as Record<string, unknown>;
      widget.setData(data);
      // await widget.refreshCallChaining?.syncCall();
    } else {
      if (isEmpty(await widget.getData())) {
        const data = (await customQuery(step.model, 'construct')) as Record<string, unknown>;
        widget.setData(data);
        // await widget.refreshCallChaining?.syncCall();
      }
    }
  }

  // region  初始化上一步下一步视图

  protected async $$beforeCreated() {
    await super.$$beforeCreated();
    let steps = this.stepJsonConfig;
    if (steps && steps.length) {
      await this.onStepChange(StepDirection.NEXT);
    }
    // 浏览器空闲就先把剩下的视图初始化掉
    window.requestIdleCallback(async () => {
      (steps || []).map(async (step) => {
        if (!this.stepViewWidget[`${step.model}_${step.viewName}`]) {
          this.initStepView(step);
        }
      });
    });
  }

  // region 提交数据

  // 保存
  @Widget.Method()
  public async onSave() {
    this.loading = true;
    const step = this.stepJsonConfig[this.currentActiveKeyIndex];
    const widget = this.stepViewWidget[`${step.model}_${step.viewName}`];
    if (!widget) {
      return;
    }

    const validatorRes = await widget.validator?.();
    if (validatorRes) {
      const submitData = (await widget.getData()) as any;
      await customMutation(step.model, 'create', submitData || {});
      this.loading = false;
    }
  }
}

NextStep.vue 多页面步骤条 vue 组件

<template>
  <div class="next-step">
    <a-steps :current="current">
      <a-step v-for="title in titles" :title="title" />
    </a-steps>
    <OioSpin :loading="loading" class="oio-spin">
      <div class="setp__main">
        <template v-for="(step, index) in stepJsonConfig">
          <div class="setp__item" v-show="currentActiveKeyIndex === index">
            <slot :name="`Form_${step.model}_${step.viewName}`" />
          </div>
        </template>
      </div>
      <div class="setp__footer" v-if="stepJsonConfig.length">
        <a-button v-if="current > 0" class="oio-button" type="primary" @click="previous"> 上一步 </a-button>
        <a-button v-if="current < stepJsonConfig.length - 1" class="oio-button" type="primary" @click="next">
          下一步
        </a-button>
        <a-button v-if="current === stepJsonConfig.length - 1" class="oio-button" type="primary" @click="finish">
          完成
        </a-button>
      </div>
    </OioSpin>
  </div>
</template>
<script setup lang="ts">
import { PropType, ref } from 'vue';
import { OioSpin } from '@oinone/kunlun-vue-ui-antd';
import { IStepConfig, StepDirection } from './type';

const props = defineProps({
  loading: {
    type: Boolean,
    default: false
  },
  titles: {
    type: Array as PropType<string[]>,
    default: []
  },
  stepJsonConfig: {
    type: Array as PropType<IStepConfig[]>,
    default: []
  },
  currentActiveKeyIndex: {
    type: Number,
    default: 0
  },
  onStepChange: {
    type: Function
  },
  onSave: {
    type: Function
  }
});

const current = ref<number>(0);

const next = () => {
  current.value++;
  props.onStepChange?.(StepDirection.NEXT);
};
const previous = () => {
  current.value--;
  props.onStepChange?.(StepDirection.PREVIOUS);
};

const finish = async () => {
  await props.onSave?.();
  window.history.back();
};
</script>
<style lang="scss" scoped>
.next-step {
  height: 100%;
  background-color: #fff;
  padding: 16px;

  .setp__main {
    display: flex;
    justify-content: flex-start;

    .setp__item {
      width: 100%;
    }
  }

  .setp__footer {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    gap: 16px;
    margin-top: 18px;
  }
}
</style>

MyMetadataViewWidget 数据隔离组件

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

/**
 * 通过视图handle查找搜索组件
 * @param viewHandle
 */
const queryFormWidgetByViewHandle = (viewHandle: string): FormWidget | null => {
  const baseViewWidget = Widget.select(viewHandle);
  const formWidget = queryDslWidget(baseViewWidget?.getChildrenInstance(), FormWidget);
  if (formWidget) {
    return formWidget as unknown as FormWidget;
  }
  return null;
};

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

  @Widget.Provide()
  public submitCallChaining: CallChaining | undefined;

  @Widget.Provide()
  public refreshCallChaining: 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 || {}];
    }
  }
  public initialize(props): this {
    this.mountedCallChaining = props.mountedCallChaining;
    this.submitCallChaining = props.submitCallChaining;
    this.refreshCallChaining = props.refreshCallChaining;
    this.dataSource = props.dataSource;
    this.activeRecords = props.activeRecords;
    super.initialize(props);
    return this;
  }

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

  public async validator() {
    const formWidget = queryFormWidgetByViewHandle(this.currentHandle);
    const res = await formWidget?.validator();
    return res;
  }

  public async getData() {
    const formWidget = queryFormWidgetByViewHandle(this.currentHandle);
    const callResult = await formWidget?.submit();
    return callResult?.records as Record<string, unknown>;
  }

  protected getModelFields() {
    const formWidget = queryFormWidgetByViewHandle(this.currentHandle);
    return formWidget?.rootRuntimeContext.getRequestModelFields();
  }

  public setData(data: Record<string, unknown>) {
    if (data) {
      this.dataSource = [data];
      this.activeRecords = [data];
    }
  }

  public getRuntimeModel() {
    return this.runtimeContext?.model;
  }
}

原理分析

参考 https://doc.oinone.top/frontend/components/21426.html

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

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

(0)
银时的头像银时数式员工
上一篇 2025年7月21日 pm4:02
下一篇 2025年7月21日 pm8:49

相关推荐

  • 前端自定义组件之左右滑动

    本文将讲解如何通过自定义,实现容器内的左右两个元素,通过左右拖拽分隔线,灵活调整宽度。其中左右元素里的内容都是界面设计器拖出来的。 实现路径 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日
    37000
  • 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日
    40000
  • oio-empty-data 空数据状态

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

    2023年12月18日
    71500
  • oio-spin 加载中

    用于页面和区块的加载中状态。 何时使用 页面局部处于等待异步数据或正在渲染过程时,合适的加载动效会有效缓解用户的焦虑。 API 参数 说明 类型 默认值 版本 delay 延迟显示加载效果的时间(防止闪烁) number (毫秒) – loading 是否为加载中状态 boolean true wrapperClassName 包装器的类属性 string –

    2023年12月18日
    63500
  • 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日
    65500

Leave a Reply

登录后才能评论