基于vue+element的动态表单的设计与实现(3)

5 篇文章 0 订阅

动态表单的设计与实现


备注:细节可能有误,主要提供思路

接着上一篇,这篇主要讲解表单的三种模式。新建模式无需多说了,我们看看更新和详情模式。

  1. 更新模式无非是对表单进行赋值回显;
  2. 详情模式则是将表单移除,仅展示具体的内容信息;
    为了避免如下拉组件需要通过value去找对应的label,建议在新建/更新时,将每个单元的value,label一并保存下来。

那么这样看来,更新模式也好、详情模式也罢,都是为表单注入数据。那么如何注入呢?
回到form-format.js

function format() {
  const $listen = {
    $publish: {},       // 发布者
    $subscribe: {},     // 订阅者
    // 新增$actionValue
    $actionValue: {},   // 动态赋值
    $actionPublish: {}, // 动态响应的发布
  };
}

修改FormItem.vue

mounted() {
  this.init();
  this.handleSubscribe();
  // 新增initActionValue
  this.initActionValue();
  this.initWatchValue();
},
methods: {
  initActionValue() {
    const { $index, $listen, component } = this.item;
    const [, groupNo, fieldId] = $index;
    const currentFieldIndex = $index.join(".");
    const actionCallback = (newValue, newLabel) => {
      this.inpValue = newValue;
      if (newLabel === undefined) {
        // 不存在的话,通过value取找对应的label
        // initChange调用各个组件的change事件,在里面去找label,并写入到formData中
        this.initChange(component, newValue);
      } else {
        // 存在就直接写入
        this.formData[groupNo][fieldId + "--label"] = newLabel;
      }
    };
    if (!$listen.$actionValue[currentFieldIndex]) {
      $listen.$actionValue[currentFieldIndex] = [];
    }
    $listen.$actionValue[currentFieldIndex].push(actionCallback);
  },
}

这边注册好了之后,在为表单组件的入口Index.vue新增一个回显的函数

/**
* 设置表单值
 */
setFieldsValue(data) {
  const { $actionValue } = this.$listen;
  this.tplList.forEach((tpl) => {
    const { groupNo, fields } = tpl;
    const groupData = data[groupNo];
    Object.keys(groupData)
      .filter((v) => v.indexOf("--label") == -1)
      .forEach((field) => {
        const key = `formData.${groupNo}.${field}`;
        $actionValue[key].forEach((f) =>
          f(groupData[field], groupData[field + "--label"])
        );
      });
  });
},

业务代码层,通过ref调用动态表单实例,调用setFieldsValue方法注入数据
如:

this.$refs["dynamic-form"].setFieldsValue({
  basic: { name: "xxx", "name--label": "xxx111" },
 });

其他细节就不写了,这边主要提供思路。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值