4.2.2 框架之MessageHub

一、MessageHub

请求出现异常时,提供”点对点“的通讯能力

二、何时使用

错误提示是用户体验中特别重要的组成部分,大部分的错误体现在整页级别,字段级别,按钮级别。友好的错误提示应该是怎么样的呢?我们假设他是这样的

  • 与用户操作精密契合
    • 当字段输入异常时,错误展示在错误框底部
    • 按钮触发服务时异常,错误展示在按钮底部
  • 区分不同的类型
    • 错误
    • 成功
    • 警告
    • 提示
    • 调试
  • 简洁易懂的错误信息

在oinone平台中,我们怎么做到友好的错误提示呢?接下来介绍我们的MessageHub,它为自定义错误提示提供无限的可能。

三、如何使用

订阅

import { useMessageHub, ILevel } from "@kunlun/dependencies"
const messageHub = useMessageHub('当前视图的唯一标识');
/* 订阅错误信息 */
messageHub.subscribe((errorResult) => {
 console.log(errorResult)
})
/* 订阅成功信息 */
messageHub.subscribe((errorResult) => {
 console.log(errorResult)
}, ILevel.SUCCESS)

图4-2-2-1 订阅的示例代码

销毁

/** 
* 在适当的时机销毁它
* 如果页面逻辑运行时都不需要销毁,在页面destroyed是一定要销毁,重要!!!
*/
messageHub.unsubscribe()

图4-2-2-2 销毁的示例代码

四、实战

让我们把3.5.7.5【自定义视图-表单】一文中的自定义表单进行改造,加入我们的messageHub,模拟在表单提交时,后端报错信息在字段下方给予提示。

Step1 (后端)重写PetType的创建函数

重写PetType的创建函数,在创建逻辑中通过MessageHub返回错误信息,返回错误信息的同时要设置paths信息方便前端处理

@Action.Advanced(name = FunctionConstants.create, managed = true)
    @Action(displayName = "确定", summary = "创建", bindingType = ViewTypeEnum.FORM)
    @Function(name = FunctionConstants.create)
    @Function.fun(FunctionConstants.create)
    public PetType create(PetType data){
        List<Object> paths = new ArrayList<>();
        paths.add("demo.PetType");
        paths.add("kind");
        PamirsSession.getMessageHub().msg(new Message().msg("kind error").setPath(paths).setLevel(InformationLevelEnum.ERROR).setErrorType(ErrorTypeEnum.BIZ_ERROR));

        List<Object> paths2 = new ArrayList<>();
        paths2.add("demo.PetType");
        paths2.add("name");
        PamirsSession.getMessageHub().msg(new Message().msg("name error").setPath(paths2).setLevel(InformationLevelEnum.ERROR).setErrorType(ErrorTypeEnum.BIZ_ERROR));
//        data.create();
        return data;
    }

图4-2-2-3 (后端)重写PetType的创建函数

Step 2 修改PetForm.vue

<template>
  <div class="petFormWrapper">
    <form :model="formState" @finish="onFinish">
      <a-form-item label="品种种类" id="name" name="kind" :rules="[{ required: true, message: '请输入品种种类!', trigger: 'focus' }]">
        <a-input v-model:value="formState.kind" @input="(e) => onNameChange(e, 'kind')" />
        <span style="color: red">{{ getServiceError('kind') }}</span>
      </a-form-item>

      <a-form-item label="品种名" id="name" name="name" :rules="[{ required: true, message: '请输入品种名!', trigger: 'focus' }]">
        <a-input v-model:value="formState.name" @input="(e) => onNameChange(e, 'name')" />
        <span style="color: red">{{ getServiceError('name') }}</span>
      </a-form-item>
    </form>
  </div>
</template>-

<script lang="ts">
import { defineComponent, reactive } from 'vue';
import { Form } from 'ant-design-vue';

export default defineComponent({
  props: ['onChange', 'reloadData', 'serviceErrors'],
  components: { Form },
  setup(props) {
    const formState = reactive({
      kind: '',
      name: '',
    });

    const onFinish = () => {
      console.log(formState);
    };

    const onNameChange = (event, name) => {
      props.onChange(name, event.target.value);
    };

    const reloadData = async () => {
      await props.reloadData();
    };
    // 提示服务器异常消息
    const getServiceError = (name: string) => {
      const error = props.serviceErrors.find(error => error.name === name);
      return error ? error.error : '';
    }

    return {
      formState,
      reloadData,
      onNameChange,
      onFinish,
      getServiceError
    };
  }
});
</script>

图4-2-2-4 修改PetForm.vue

Step3 PetFormViewWidget.ts

import { constructOne, FormWidget, queryOne, SPI, ViewWidget, Widget, IModel, getModelByUrl, getModel, getIdByUrl, FormWidgetV3, CustomWidget, MessageHub, useMessageHub, ILevel, CallChaining } from '@kunlun/dependencies';
import PetFormView from './PetForm.vue';

@SPI.ClassFactory(CustomWidget.Token({ widget: 'PetForm' }))
export class PetFormViewWidget extends FormWidgetV3 {
  public initialize(props) {
    super.initialize(props);
    this.setComponent(PetFormView);
    return this;
  }

  /**
   * 数据提交
   * @protected
   */
  @Widget.Reactive()
  @Widget.Inject()
  protected callChaining: CallChaining | undefined;

  private modelInstance!: IModel;

  // MessageHub相关逻辑
  private messageHub!: MessageHub;

  @Widget.Reactive()
  private serviceErrors: Record<string, unknown>[] = [];

  /**
   * 重要!!!!
   * 当字段改变时修改formData
   * */
  @Widget.Method()
  public onFieldChange(fieldName: string, value) {
    this.setDataByKey(fieldName, value);
  }

  /**
   * 表单编辑时查询数据
   * */
  public async fetchData(content: Record<string, unknown>[] = [], options: Record<string, unknown> = {}, variables: Record<string, unknown> = {}) {
    this.setBusy(true);
    const context: typeof options = { sourceModel: this.modelInstance.model, ...options };
    const fields = this.modelInstance?.modelFields;
    try {
      const id = getIdByUrl();
      const data = (await queryOne(this.modelInstance.model, (content[0] || { id }) as Record<string, string>, fields, variables, context)) as Record<string, unknown>;

      this.loadData(data);
      this.setBusy(false);
      return data;
    } catch (e) {
      console.error(e);
    } finally {
      this.setBusy(false);
    }
  }

  /**
   * 新增数据时获取表单默认值
   * */
  @Widget.Method()
  public async constructData(content: Record<string, unknown>[] = [], options: Record<string, unknown> = {}, variables: Record<string, unknown> = {}) {
    this.setBusy(true);
    const context: typeof options = { sourceModel: this.modelInstance.model, ...options };
    const fields = this.modelInstance.modelFields;
    const reqData = content[0] || {};
    const data = await constructOne(this.modelInstance!.model, reqData, fields, variables, context);
    return data as Record<string, unknown>;
  }

  @Widget.Method()
  private async reloadData() {
    const data = await this.constructData();
    // 覆盖formData
    this.setData(data);
  }

  @Widget.Method()
  public onChange(name, value) {
    this.formData[name] = value;
  }

  protected async mounted() {
    super.mounted();
    const modelModel = getModelByUrl();
    this.modelInstance = await getModel(modelModel);
    this.fetchData();
    this.messageHub = useMessageHub('messageHubCode');
    this.messageHub.subscribe((result) => {
      this.serviceErrors = [];
      // 收集错误信息
      if (Array.isArray(result)) {
        const errors = result.map((res) => {
          const path = res.path[1],
            error = res.message;
          return {
            name: path,
            error
          };
        });
        this.serviceErrors = errors;
      }
    });
    this.messageHub.subscribe((result) => {
      console.log(result);
    }, ILevel.SUCCESS);
    // 数据提交钩子函数!!!
    this.callChaining?.callBefore(() => {
      return this.formData;
    });
  }
}

图4-2-2-5 PetFormViewWidget.ts

Step4 刷新页面看效果

image.png

图4-2-2-6 刷新页面看效果

Oinone社区 作者:史, 昂原创文章,如若转载,请注明出处:https://doc.oinone.top/oio4/9303.html

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

(0)
史, 昂的头像史, 昂数式管理员
上一篇 2024年5月23日 am8:35
下一篇 2024年5月23日

相关推荐

  • 3.5.7.5 自定义动作

    动作是什么 动作(action)描述了终端用户的各种操作。这些操作可以涉及多个层面,包括但不限于: 页面间的跳转:用户可以通过动作从一个页面跳转到另一个页面。 业务交互:动作可以触发与后端服务的交互,例如提交表单、请求数据等。 界面操作:动作可以用于打开模态对话框、抽屉(侧边栏)等界面元素。 作用场景 Oinone 平台内置了一系列的基础动作,默认实现了常见的功能,如页面跳转、业务交互和界面操作等。这些内置动作旨在满足大多数标准应用场景的需求,简化开发过程,提高开发效率。以下是一些常见的内置动作示例: 页面跳转:允许用户在不同页面间导航。 业务交互:支持与后端服务的数据交互,如提交表单。 界面操作:提供动态返回上一页、校验表单、关闭弹窗等。 自定义动作的需求场景 尽管内置动作覆盖了许多常规需求,但在某些复杂或特定的业务场景中,可能需要更加个性化的处理。这些场景可能包括: 特殊的业务逻辑:需要执行不同于标准流程的特定业务操作。 个性化的用户界面:标准的 UI 组件无法满足特定的设计要求。 高级交互功能:需要实现复杂的用户交互和数据处理。 扩展和定制动作 为了满足这些特定需求,Oinone 平台支持通过继承和扩展来自定义动作。开发者可以通过以下步骤实现自定义动作: 继承基类:从平台提供的动作基类继承,这为自定义动作提供了基础框架和必要的接口。 实现业务逻辑:在继承的基础上,添加特定的业务逻辑实现。 自定义界面:根据需要调整或完全重写界面组件,以符合特定的UI设计。 集成测试:确保自定义动作在各种情况下的稳定性和性能。 最佳实践 明确需求:在进行扩展之前,清楚地定义业务需求和目标。 重用现有功能:尽可能利用平台的内置功能和组件。 保持一致性:确保自定义动作与平台的整体风格和标准保持一致。 充分测试:进行全面的测试,确保新动作的稳定性和可靠性。 案例分析 假设有一个场景,需要一个特殊的数据提交流程,该流程不仅包括标准的表单提交,还涉及复杂的数据验证和后续处理。在这种情况下,可以创建一个自定义动作,继承基础动作类并实现特定的业务逻辑和用户界面。 自定义动作 自定义跳转动作 示例工程目录 以下是需关注的工程目录示例,main.ts更新导入./action,action/index.ts更新导出./custom-viewactioin: 图3-5-7-24 自定义跳转动作工程目录示例 步骤 1: 创建自定义动作类 首先,您创建了一个名为 CustomViewAction 的类,这个类继承自 RouterViewActionWidget。这意味着自定义动作是基于路由视图动作的,这通常涉及页面跳转或导航。 import {ActionWidget, RouterViewActionWidget, SPI} from '@kunlun/dependencies'; import CustomViewActionVue from './CustomViewAction.vue'; @SPI.ClassFactory( ActionWidget.Token({ model: 'resource.ResourceCity', name: 'redirectCreatePage' }) ) export class CustomViewAction extends RouterViewActionWidget { public initialize(props) { super.initialize(props); this.setComponent(CustomViewActionVue); return this; } } 图3-5-7-24 自定义跳转动作组件(TS)代码示例 @SPI.ClassFactory: 这是一个装饰器,用于向平台注册这个新的动作。 ActionWidget.Token: 通过这个Token,指定了这个动作与特定模型 (resource.ResourceCity) 关联,并给这个动作命名 (redirectCreatePage). 步骤 2: 初始化和设置组件 在 initialize 方法中,调用了父类的初始化方法,并设置了自定义的 Vue 组件。 public initialize(props) { super.initialize(props); this.setComponent(CustomViewActionVue); return this; } 图3-5-7-24 初始化和设置组件 步骤 3: 定义 Vue 组件 在 CustomViewAction.vue 文件中,定义了自定义动作的视觉表示。 <template> <div class="view-action-wrapper"> 自定义挑战跳转动作 </div> </template> <script lang="ts"> import { defineComponent } from 'vue' export default defineComponent({ inheritAttrs: false, name: 'ViewActionComponent' }) </script> <style lang="scss"> .view-action-wrapper { } </style> 图3-5-7-24 自定义跳转动作组件(Vue)代码示例 步骤 4: 效果如下 图3-5-7-24 自定义跳转动作效果示例 自定义服务器动作 示例工程目录 以下是需关注的工程目录示例,action/index.ts更新导出./custom-serveraction: 图3-5-7-24 自定义服务器动作工程目录示例 步骤 1: 创建自定义动作类 首先, 创建了一个名为 CustomServerAction 的类,这个类继承自 ServerActionWidget。这表明您的自定义动作主要关注服务器端的逻辑。 import {ActionWidget, ServerActionWidget, SPI, Widget} from '@kunlun/dependencies'; import CustomServerActionVue from './CustomServerAction.vue'; @SPI.ClassFactory( ActionWidget.Token({ model: 'resource.ResourceCity', name: 'delete' })…

    2024年5月23日
    1.0K00
  • 4.2.5 框架之网络请求-Request

    在中后台业务场景中,大部分的请求时候是可以被枚举的,比如创建、删除、更新、查询。在上文中,我们讲了httpClient如何自定义请求,来实现自己的业务诉求。本文中讲到的Request是离业务更近一步的封装,他提供了开箱即用的API,比如insertOne、updateOne,它是基于HttpClient做的二次封装,当你熟悉Request时,在中后台的业务场景中,所有的业务接口自定义将事半功倍。 一、Request详细介绍 元数据-model 获取模型实例 import { getModel } from '@kunlun/dependencies' getModel('modelName'); 图4-2-5-1 获取模型实例 清除所有缓存的模型 import { cleanModelCache } from '@kunlun/dependencies' cleanModelCache(); 图4-2-5-2 清除所有缓存的模型 元数据-module 获取应用实例,包含应用入口和菜单 import { queryModuleByName } from '@kunlun/dependencies' queryModuleByName('moduleName') 图4-2-5-3 获取应用实例 查询当前用户所有的应用 import { loadModules } from '@kunlun/dependencies' loadModules() 图4-2-5-4 查询当前用户所有的应用 query 分页查询 import { queryPage } from '@kunlun/dependencies' queryPage(modelName, { pageSize: 15, // 一次查询几条 currentPage, 1, // 当前页码 condition?: '' // 查询条件 maxDepth?: 1, // 查几层模型出来,如果有2,会把所有查询字段的关系字段都查出来 sort?: []; // 排序规则 }, fields, variables, context) 图4-2-5-5 分页查询 自定义分页查询-可自定义后端接口查询数据 import { customQueryPage } from '@kunlun/dependencies' customQueryPage(modelName, methodName, { pageSize: 15, // 一次查询几条 currentPage, 1, // 当前页码 condition?: '' // 查询条件 maxDepth?: 1, // 查几层模型出来,如果有2,会把所有查询字段的关系字段都查出来 sort?: []; // 排序规则 }, fields, variables, context) 图4-2-5-6 自定义分页查询 查询一条-根据params匹配出一条数据 import { queryOne } from '@kunlun/dependencies' customQueryPage(modelName, params, fields, variables, context) 图4-2-5-7 根据params匹配出一条数据 自定义查询 import { customQuery } from '@kunlun/dependencies' customQuery(methodName, modelName, record, fields, variables, context) 图4-2-5-8 自定义查询 update import { updateOne } from '@kunlun/dependencies' updateOne(modelName, record, fields, variables, context) 图4-2-5-9 update insert import { insertOne } from '@kunlun/dependencies' insertOne(modelName, record, fields, variables, context) 图4-2-5-10 insert delete import { deleteOne } from '@kunlun/dependencies'…

    2024年5月23日
    1.1K00
  • 4.1.5 模型之持久层配置

    一、批量操作 批量操作包括批量创建与批量更新。批量操作的提交类型系统默认值为batchCommit。 批量提交类型: useAffectRows,循环单次单条脚本提交,返回实际影响行数 useAndJudgeAffectRows,循环单次单条脚本提交,返回实际影响行数,若实际影响行数与输入不一致,抛出异常 collectionCommit,将多个单条更新脚本拼接成一个脚本提交,不能返回实际影响行数 batchCommit,使用单条更新脚本批量提交,不能返回实际影响行数。 全局配置 pamirs: mapper: batch: batchCommit 图4-1-5-1 全局配置 运行时配置 非乐观锁模型系统默认采用batchCommit提交更新操作;乐观锁模型默认采用useAndJudgeAffectRows提交更新操作。也可以使用以下方式在运行时改变批量提交方式。 Spider.getDefaultExtension(BatchApi.class).run(() -> { 更新逻辑 }, 批量提交类型枚举); 图4-1-5-2 运行时配置 运行时校正 如果模型配置了数据库自增主键,而批量新增的批量提交类型为batchCommit,则系统将批量提交类型变更为collectionCommit(如果使用batchCommit,则需要单条提交以获得正确的主键返回值,性能有所损失)。 如果模型配置了乐观锁,而批量更新的批量提交类型为collectionCommit或者batchCommit,则系统将批量提交类型变更为useAndJudgeAffectRows。也可以失效乐观锁,让系统不做批量提交类型变更处理。 二、乐观锁(举例) 在一些会碰到并发修改的数据,往往需要进行并发控制,一般数据库层面有两种一种是悲观锁、一种是乐观锁。oinone对乐观锁进行了良好支持 定义方式 乐观锁的两种定义方式: 通过快捷继承VersionModel,构建带有乐观锁,唯一编码code且主键为id的模型。 可以在字段上使用@Field.Version注解来标识该模型更新数据时使用乐观锁 如果更新的实际影响行数与入参数量不一致,则会抛出异常,错误码为10150024。如果是批量更新数据,为了返回准确的实际影响行数,批量更新由批量提交改为循环单条数据提交更新,性能有所损失。 失效乐观锁 一个模型在某些场景下需要使用乐观锁来更新数据,而另一些场景不需要使用乐观锁来更新数据,则可以使用以下方式在一些场景下失效乐观锁。更多元位指令用法详见4.1.9【函数之元位指令】一文。 PamirsSession.directive().disableOptimisticLocker(); try{ 更新逻辑 } finally { PamirsSession.directive().enableOptimisticLocker(); } 图4-1-5-3 失效乐观锁 不抛乐观锁异常 将批量提交类型设置为useAffectRows即可,这样可改由外层逻辑对返回的实际影响行数进行自主判断。 Spider.getDefaultExtension(BatchApi.class).run(() -> { 更新逻辑,返回实际影响行数 }, BatchCommitTypeEnum.useAffectRows); 图4-1-5-4 将批量提交类型设置为useAffectRows 构建第一个VersionModel Step1 新建PetItemInventroy模型,继承快捷模型VersionModel package pro.shushi.pamirs.demo.api.model; import pro.shushi.pamirs.meta.annotation.Field; import pro.shushi.pamirs.meta.annotation.Model; import pro.shushi.pamirs.meta.base.common.VersionModel; import java.math.BigDecimal; @Model.model(PetItemInventroy.MODEL_MODEL) @Model(displayName = "宠物商品库存",summary="宠物商品库存",labelFields = {"itemName"}) public class PetItemInventroy extends VersionModel { public static final String MODEL_MODEL="demo.PetItemInventroy"; @Field(displayName = "商品名称") private String itemName; @Field(displayName = "库存数量") private BigDecimal quantity; } 图4-1-5-5 新建PetItemInventroy模型 Step2 修改DemoMenu,增加访问入口 @UxMenu("商品库存")@UxRoute(PetItemInventroy.MODEL_MODEL) class PetItemInventroyMenu{} 图4-1-5-6 修改DemoMenu Step3 重启看效果 体验一:页面上新增、修改数据库字段中的opt_version会自动加一 图4-1-5-7 示例效果一 图4-1-5-8 示例效果二 图4-1-5-9 示例效果三 图4-1-5-10 示例效果四 体验二:同时打两个页面,依次点击,您会发现一个改成功,一个没有改成功。但页面都没有报错,只是update返回影响行数一个为1,另一个为0而已。 图4-1-5-11 编辑宠物商品库存 图4-1-5-12 宠物商品库存列表 注:增加了乐观锁,我们在写代码的时候一定要注意,单记录更新操作的时候要去判断返回结果(影响行数),不然没改成功,程序是不会抛错的。不像batch接口默认会报错 Step4 预留任务:重写PetItemInventroy的update函数 留个任务,请各位小伙伴自行测试玩玩,这样会更有体感 package pro.shushi.pamirs.demo.core.action; import org.springframework.stereotype.Component; import pro.shushi.pamirs.demo.api.enumeration.DemoExpEnumerate; import pro.shushi.pamirs.demo.api.model.PetItemInventroy; import pro.shushi.pamirs.demo.api.model.PetTalent; import pro.shushi.pamirs.meta.annotation.Function; import pro.shushi.pamirs.meta.annotation.Model; import pro.shushi.pamirs.meta.common.exception.PamirsException; import pro.shushi.pamirs.meta.constant.FunctionConstants; import pro.shushi.pamirs.meta.enmu.FunctionOpenEnum; import pro.shushi.pamirs.meta.enmu.FunctionTypeEnum; import java.util.ArrayList; import java.util.List; @Model.model(PetItemInventroy.MODEL_MODEL) @Component public class PetItemInventroyAction { @Function.Advanced(type= FunctionTypeEnum.UPDATE) @Function.fun(FunctionConstants.update) @Function(openLevel = {FunctionOpenEnum.API}) public PetItemInventroy update(PetItemInventroy data){ List<PetItemInventroy> inventroys = new ArrayList<>(); inventroys.add(data); //批量更新会,自动抛错 int i =…

    2024年5月23日
    99300
  • 企业个性化配置

    平台除了帮助企业快速解决业务需求外,还提供了企业文化、风格个性化能力,本章节详细介绍个性化配置。包括:登陆页配置、企业形象配置、系统风格配置。 系统配置 配置入口 配置入口:右上角登陆账号——系统配置——全局配置——登陆页配置、企业形象配置、系统风格配置。 登陆页配置 用户自定义登陆页的主题,一共有六个主题可选择,分别为: 图一:左侧是图片,右侧是登录输入框,Logo在左上角; 图二:右左侧是图片,右侧是登录输入框,Logo在左上角; 图三:底图是图片,登录输入框浮在页面左侧,Logo在左上角; 图四:底图是图片,登录输入框浮在页面中间,Logo在左上角; 图五:底图是图片,登录输入框浮在页面右侧,Logo在左上角; 图六:底图是图片,登录输入框浮在页面中间,Logo在登录框上方。 页面背景 上传登录页背景,支持上传jpg、png格式的图片或mp4、mov、avi格式视频。尺寸建议为1920*1080px,文件大小不超过50MB。 登录页logo:指配置登录页左上角的logo图标。 预览:配置后可在右侧电脑中点击全屏预览效果。 配置示例 企业形象配置 企业形象配置:可设置企业信息、业务应用导航栏logo、浏览器logo,设置完成之后,点击发布之后设置生效。 系统风格配置 系统风格配置,可设置主题(浅色、深色)、尺寸(大、中、小),配置后可全屏预览,发布后即可更换成对应的风格。 下载代码可进行自定义风格。

    2024年6月20日
    1.0K00
  • 第1章 揭开面纱,理解Oinone

    本章旨在从以下几个维度逐步揭开Oinone的面纱,让大家了解Oinone的初心与愿景,以及它是如何站在软件领域的巨人肩膀上,结合企业数字化转型的深入,形成全新的理念,帮助企业完成数字化转型。 具体来说,本章会从以下四个方面逐一展开: Oinone的初心与愿景:结合中国软件行业的发展与自身职业发展经历,探讨Oinone为何诞生以及其愿景是什么。 Oinone致敬西方软件行业的新贵odoo:介绍Oinone的灵感来源,探究Oinone与odoo的异同,以及如何从odoo中汲取经验。 从企业转型困境,引出Oinone新的思路:通过剖析企业数字化转型的困境,引出Oinone提出的全新思路,以及如何应对企业数字化转型的挑战。 行业对比,让您从不同视角理解Oinone:通过与同行业产品进行对比,从不同的视角深入理解Oinone的特点和优势。

    Oinone 7天入门到精通 2024年5月23日
    2.5K00

Leave a Reply

登录后才能评论