Vue3+ElementPlus表格table/v-for表单校验

Element Plus 如果需要对表格/列表数据进行表单校验,首先需要更改 form 绑定的 model 数据

const form = ref({
	tableData: [] // 表格数据/需要v-for遍历的数据
})

然后将 el-form-item 的 props 修改为如下(格式:表格数据 + 索引 + 需要校验的值),最后加上 rules。v-for 渲染的表单同此

<el-form-item
  :prop="'tableData.' + scope.$index + '.value'"
  :rules="formRules.value"
>
  <el-input v-model="scope.row.value">el-input>
el-form-item>

完整代码

<template>
  <div class="p-10">
    <div class="mb-4">
      <el-button type="primary" @click="handleAdd">Addel-button>
      <el-button @click="handleValidate">Validel-button>
    div>
    <el-form ref="formRef" :model="form">
      <el-table :data="form.tableData" border>
        <el-table-column prop="id" label="Id">el-table-column>
        <el-table-column prop="name" label="Name">el-table-column>
        <el-table-column label="Value">
          <template #default="scope">
            <el-form-item
              :prop="'tableData.' + scope.$index + '.value'"
              :rules="formRules.value"
            >
              <el-input v-model="scope.row.value">el-input>
            el-form-item>
          template>
        el-table-column>
      el-table>
    el-form>
  div>
template>

<script setup lang="ts">
import { ref } from 'vue'
import { type FormInstance } from 'element-plus'

const form = ref({
  tableData: [
    {
      id: 1,
      name: '1',
      value: ''
    },
    {
      id: 2,
      name: '2',
      value: ''
    },
    {
      id: 3,
      name: '3',
      value: ''
    }
  ]
})
const formRules = ref({
  value: [
    {
      required: true,
      message: 'Please input value',
      trigger: 'blur'
    }
  ]
})

const handleAdd = () => {
  form.value.tableData.push({
    id: form.value.tableData.length + 1,
    name: '' + (form.value.tableData.length + 1),
    value: ''
  })
}

const formRef = ref<FormInstance>()
const handleValidate = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log('success')
    } else {
      console.log('error')
    }
  })
}
script>

示例:
Vue3+ElementPlus表格table/v-for表单校验_第1张图片

你可能感兴趣的:(前端,Vue,vue.js,javascript,elementui)