likes
comments
collection
share

可编辑表格校验问题

作者站长头像
站长
· 阅读数 29
    <Table
      class="bottom"
      :columns="basicColumns"
      :data-source="line"
      :pagination="false"
      bordered
      :scroll="{
        x: 100 + '%',
        y: true,
      }"
    >
      <template #input="{ record, column, text }">
        <Form
          :ref="form"
          :model="editableData"
          :rules="{ [record.key]: [record.rule] }"
          :scrollToFirstError="true"
        >
          <FormItem :name="[record.key]">
            <Input
              v-if="record.type === 'input'"
              :disabled="props.type === 1"
              :title="editableData[record.key]?.toString()"
              v-model:value="editableData[record.key]"
              @change="change(record, column)"
            />
          </FormItem>
        </Form>
      </template>
    </Table>

这是一个封装可编辑表格的例子,现在我们生成表格。

可编辑表格校验问题 之后,当我们输入完成,想要校验的时候,便会发现全部可以通过校验,即便是不符合校验规则的数据。

这是为什么?

看这段代码。

<Form
 :ref="form"
 :model="editableData"
 :rules="{ [record.key]: [record.rule] }"
 :scrollToFirstError="true"
>

仔细检查代码,便会发现,我们使用表单ref属性进行校验的。

那么表格渲染的时候,ref只代表最后一个输入框,此时自然不会校验其他输入框,校验便会通过。

如何解决?

可以把ref写成函数形式。

储存到一个变量中,校验的时候,全部校验一遍就可以了。

        <Form
          :ref="(el) => handleSetInputMap(el, record.key)"
          :model="editableData"
          :rules="{ [record.key]: [record.rule] }"
          :scrollToFirstError="true"
        >
        
          function handleSetInputMap(el, key) {
            formRef.value[dataIndex][key] = el;
          }

如此bug便解决。

转载自:https://juejin.cn/post/7368413106677088271
评论
请登录