Vue3项目Element-plus-UI Form 表单组件二次封装

871 阅读1分钟

项目需要基于 Vue3 + Element-plus 封装的 Form 组件进行二次封装,支持所有 Element-plus Form 组件配置项

表单组件已给 el-form 绑定 ref 并用 defineExpose 暴露出来,我们只需要在引入组件中绑定ref,即可调用 el-form 的方法

<template>
  <el-form :model="model" v-bind="$attrs" v-on="$listeners" ref="formRef">
    <el-form-item
      v-for="item in columns"
      :key="item.Name"
      :label="item.Description + ':'"
      :prop="item.Name"
      :label-width="labelWidth"
    >
        <!-- 内容 -->
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref } from 'vue'

const formRef = ref(null)

defineExpose({
  formRef
})
</script>

使用方法:

<template>
    <af-form
        :columns="formColumns"
        :model="addform"
        :rules="addRules"
        :inline="true"
        :label-width="formLabelWidth"
        ref="addFormRef"
      ></af-form>
</template>
<script setup>
import { getCurrentInstance, reactive, ref, watch, markRaw } from 'vue'

const formColumns = [
  { Type: '', Description: '名称', Name: 'Name' },
  { Type: '', Description: '说明', Name: 'Description' },
  {Type: '',Description: '执行间隔',Name: 'Interval'}
  
 addFormRef.value.formRef.validate(async (valid) => {
    console.log('valid')
 })
</script>