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 Oinone以交互为外在

    交互组件(UI Componment): 用组件化的方式统一管理:菜单、布局、视图 用Action做衔接,来勾绘出模块的前端交互拓扑,描述所有可操作行为 oinone的页面路由串联规则是以菜单为导航,用Action做衔接,用View做展示,详见3.5.2.1View的【整体介绍】。 本章节会重点介绍: 如何定义菜单、视图、行为以及其初始化 xml配置:视图配置(包括字段联动)、字段配置、布局配置、动作配置 前端组件自定义

  • 第5章 Oinone的CDM

    2024年5月23日
    88900
  • 开放平台

    1. 开放介绍 开放平台是将 Oinone 平台内的能力向外开放,如开放商品信息查询接口、发货单查询接口等。 包括开放接口、三方应用管理。 2. 开放接口 管理开放接口信息,基本操作包括:新增、编辑、停用/启用。 2.1. 新增接口 定义API名称,选择业务域、关联模型,方法支持GET/POST/PUT/DELETE,配置接口参数、响应结果等信息。 2.2. 编辑接口 编辑需要填写的内容同新增,不做赘述。 2.3. 停用/启用 新增后为已启用,停用后,API将无法访问,请慎重使用;针对停用的API进行启用。 3. 应用管理 管理开放接口集成的外部应用,基本操作包括:新增、查看密钥、授权调整、停用/启用。 3.1. 新增应用 新增应用时,输入应用名称,选择数据传输加密算法AES密钥或RSA公钥,勾选授权的API接口。 3.2. 停用/启用 新增后为已启用,停用后,应用将无法访问授权的接口,请慎重使用;针对停用的应用可进行启用。 3.3. 查看密钥 点击【查看密钥】,弹窗展示当前 API Secret,支持复制。 3.4. 授权调整 指调整当前应用的授权的API 范围。

    2024年6月20日
    1.5K00
  • 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.0K00

Leave a Reply

登录后才能评论