vue3 for循环中使用ref进行el-from校验

应用场景:
当我使用element 中form表单 自定义多个input 提交,并且校验是否正确的时候,要从单个绑定获取多个 ref,请将 ref 绑定到一个更灵活的函数上

<template>
  <div class="operate">
    <div
      v-for="item in labelList"
      :key="item.keyword_id"
      class="refer-warp"
      :ref="itemRefs"
      :class="!multipleList.includes(item.keyword_id)?'':'ref-update'"
    >
    	<el-form
            :ref="el => { if (el) listFormRefs[item.keyword_id] = el }"
            :model="item"
            :rules="resourceSettingKeysRule"
          >
            <el-form-item prop="name">
              <el-input
                class="w-50 m-2"
                v-model="item.name"
                size="small"
                :placeholder="item.name"
                maxlength="23"
              />
            </el-form-item>
          </el-form>
     </div>
  </div>
</template>

<script setup>
import { ref, toRefs, reactive, onBeforeUpdate, onUpdated } from 'vue'
import { formInputNameValidation } from '@/utils/validator.js'

const props = defineProps({
  labelList: {
    type: Array
  },
  multipleList: {
    type: Array
  },
})
const { labelList } = toRefs(props)
const listFormRefs = ref([]);

onBeforeUpdate(() => {
  console.log('onBeforeUpdate...');
  listFormRefs.value = [];
})


// 校验规则
const resourceSettingKeysRule = reactive({
  name: [
    {
      required: true,
      message: '关键词不能为空',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 22,
      message: '关键词最多输入22个字符',
      trigger: 'change'
    },
    {
      message: '您输入的符号不合规范',
      trigger: 'blur'
    },
    { validator: formInputNameValidation, trigger: 'blur' }
  ]
})

const resourceFormRef = ref(null)
const handleSave = async (item) => {
  try {
    listFormRefs.value[item.keyword_id].validate((valid) => {
      if (valid) {
        console.log(1)
        emit('save-list-item', {
          keyword_id: item.keyword_id,
          name: item.name,
          content: item.content
        })
      }
    })
  } catch (error) {
    console.log(error)
  }
}

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