Elegant writing of form events in Vue3

Because V3 has high support for TS, some components or writing methods are not as free as V2, such as the basic skills of the front end: form events , which can be seen in the Element-Plus component library

<template>
 <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
    :size="formSize"
    status-icon
  >
 <el-form-item>
     <el-button type="primary" @click="submitForm(ruleFormRef)">
      校验
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">清空</el-button>
    </el-form-item>
</el-form>
</template>
<script lang="ts" setup>
    import { reactive, ref } from 'vue'
    import type { FormInstance, FormRules } from 'element-plus'
    const formSize = ref('default')
    const ruleFormRef = ref<FormInstance>()
    const ruleForm = reactive({})const rules = reactive<FormRules>({})
    const submitForm = async (formEl: FormInstance | undefined) => {
      if (!formEl) return
      await formEl.validate((valid, fields) => {
        if (valid) {
          console.log('submit!')
        } else {
          console.log('error submit!', fields)
        }
      })
    }

    const resetForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return
      formEl.resetFields()
    }

</script>

This is the simple version I picked up from the component library. From here, we can see that our commonly used verification method and form clearing method are too troublesome, and it is very troublesome to pass a ref, so I found a new one. method to solve this problem, the degree of freedom is almost the same as V2, that is  ref.value?.XXX() , take the above code as an example

   const submitForm  = async() => {
     if (!ruleFormRef) return
        const valid = await ruleFormRef.value.validate()
        if (!valid) return
    }
    const resetForm = async() => {
        ruleFormRef.value?.resetFields()
    }

Using this form method is firstly more concise, there will be no redundant code, better readability, and no need to pass parameters. For coders who have been using V2 to develop projects before me, I I like this one more, easy to understand.

Guess you like

Origin blog.csdn.net/css_javascrpit/article/details/131210027