Tencent / tdesign-vue-next

A Vue3.x UI components lib for TDesign.
https://tdesign.tencent.com/vue-next
MIT License
1.35k stars 445 forks source link

[Form] 数组生成的 :name="`a[${index}].b`" 在 rules 校验时想针对 index 进行区别处理,希望能像其他库一样 validator 函数增加 rule 形参 #4324

Open forever-z-133 opened 1 week ago

forever-z-133 commented 1 week ago

这个功能解决了什么问题

需求大致如下伪代码,某功能配置中需要录入多个项目名称,然后每个项目名称都得调接口验一下全局唯一。

因为是个数组,且需要先找到相应行数,才能判断是否与历史数据不同,之后再调接口。但组件库缺少取得行数的方式。

const action = 'create'; // create/modify
const data = { xxx: [{ projectName: '' }] };

const rules = {
  projectName: [
    {
      validator: async (val, rule) => {
        const valueChanged = data.xxx.find((_, index) => index === rule.index)?.projectName !== val;
        const needCheck = action === 'create' || (action === 'modify' && valueChanged);
        if (needCheck && (await checkProjectUnique({ name: val }))) {
          return { result: false, message: '项目名称重复', type: 'error' };
        }
        return true;
      }
    }
  ]
}
<t-form :data="data" :rules="rules">
  <template v-for="(item, index) in detail.xxx" :key="index">
    <t-form-item label="环境名" :name="`projectEnvRelations[${index}].projectName`" :rule-context="{ index }">
      <t-input v-model="item.projectName" placeholder="请输入,如dj-20140624,需全局唯一" />
    </t-form-item>
  </template>
</t-form>

你建议的方案是什么

rules 中的 validator 函数增加 rule 形参,值由 <form-item rule-context> 属性来传入。当然具体也可以由贵框架来设计。

github-actions[bot] commented 1 week ago

👋 @forever-z-133,感谢给 TDesign 提出了 issue。 请根据 issue 模版确保背景信息的完善,我们将调查并尽快回复你。