基于element-plus定义表单配置化扩展表单按钮

本文介绍了如何在后台管理系统中使用Element-Plus定义表单配置,特别是新增的btn.vue组件,通过props传递参数动态生成按钮,包括类型、样式和事件处理。并展示了在实体类、页面和模板中的应用示例。


前言

在后台管理系统一般都存在列表查询,且可输入数据进行查询

基于element-plus定义表单配置化

新增按钮配置化
在这里插入图片描述


一、新增btn.vue组件

<template>
  <template v-for="(btn, index) in fieldProperty.btns" :key="btn + index">
    <el-button
      @click="btn.fun"
      :size="fieldProperty.size"
      :name="btn.name"
      :readonly="btn.readonly"
      :disabled="btn.disabled"
      :type="btn.type"
      :color="btn.color"
      :dark="btn.dark"
      :plain="btn.plain"
      :round="btn.round"
      :circle="btn.circle">
      <SvgIcon v-if="btn.icon" :icon-class="btn.icon"/>
      {{ btn.name }}
    </el-button>
  </template>
</template>
<script lang="ts">
import { computed, reactive } from "vue";
import SvgIcon from "@/components/svg-icon/index.vue";
export default {
  components: { SvgIcon },
  name: "Radio",
  props: {
    modelvalue: [Boolean],
    property: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  setup(props, { emit }) {
    const fieldProperty = reactive({
      size: "default", // 'large' | 'default' | 'small'
      btns: [{
        fun: () => { console.log('Save') },
        name: 'Save',
        readonly: false,
        disabled: false,
        type: "primary", // 'primary'| 'success'| 'warning'| 'danger'| 'info'| 'text'(delete)
        color: "#334343",
        icon: 'save', // 图标
        dark: false, // dark 模式, 意味着自动设置 color 为 dark 模式的颜色 和color一起设置
        plain: false, // 是否为朴素按钮
        round: false, // 是否为圆角按钮
        circle: true, // 是否为圆形按钮
        // loading: false, // 是否为加载中状态
        // 'loading-icon': 'Loading', // 自定义加载中状态图标组件
      }],
      ...props.property,
    });
    const val = computed({
      get() {
        return props.modelvalue;
      },
      set(val) {
        emit("update:modelvalue", val); // 触发
      },
    });
    return {
      val,
      fieldProperty,
    };
  },
};
</script>
<style lang="less" scoped></style>

  • form.vue新增btn组件引入
import Btn from "@/components/form-configuration/btn.vue";
export default {
  components: {
 	...
    Btn
  },
}

二、使用

  • entity.ts
import { ObjectEntries } from "@/entity/objectentries";
import enableStatus from "@/enum/enable-status";
import type { Rules, DefaultFields, FormData } from "@/interface/form";
import { useI18n } from "vue-i18n";
export class UserSearchFormEntity extends ObjectEntries {
  public formRules: Rules = {};
  public formFields: DefaultFields = {};
  public formData: FormData = {};
  constructor() {
    const { t } = useI18n()
    super()
    this.formFields = {
      userName: "",
      nickName: "",
      phoneNumber: "",
      status: "",
      createDate: [],
    };
    this.formData = {
      userName: {
        type: "Input",
        colSize: 8,
        show: true,
        class: [],
        title: t('userName'),
        field: "userName",
        property: {
          type: "text",
          placeholder: "text",
        },
      },
      nickName: {
        type: "Input",
        colSize: 8,
        show: true,
        class: [],
        title: t('nickName'),
        field: "nickName",
        property: {
          type: "text",
          placeholder: "text",
        },
      },
      phoneNumber: {
        type: "Input",
        colSize: 8,
        show: true,
        class: [],
        title: t('phoneNumber'),
        field: "phoneNumber",
        property: {
          type: "text",
          placeholder: "text",
        },
      },
      status: {
        type: "Select",
        colSize: 8,
        show: true,
        class: [],
        title: t('status'),
        field: "status",
        property: {
          data: UserSearchFormEntity.objectEntries(enableStatus),
        },
      },
      createDate: {
        type: "Date",
        colSize: 8,
        show: true,
        class: [],
        title: t('createDate'),
        field: "createDate",
        property: {
          type: "daterange",
          placeholder: "text",
        },
      },
      btn: {
        type: "Btn",
        colSize: 8,
        show: true,
        class: ['noLabel'],
        field: "btn",
        property: {
          btns: []
        },
      },
    };
  }
}

  • page/index.ts
import { defineComponent, reactive, ref } from 'vue'
import FormList from "@/components/form-configuration/form.vue";
import { UserSearchFormEntity } from './composables/entity';
import { useI18n } from 'vue-i18n';

export default defineComponent({
  components: {
    FormList
  },
  setup() {
    const { t } = useI18n()
    const userSearchFormRef = ref()
    const userSearchFormEntity = reactive(new UserSearchFormEntity())
    userSearchFormEntity.formData.btn.property.btns = [
      {
        fun: () => {},
        name: t('search'),
        type: 'primary',
        icon: 'search'
      },
      {
        fun: () => {},
        name: t('reset'),
        icon: 'refresh',
      },
    ]
    return {
      userSearchFormRef,
      userSearchFormEntity
    };
  },
});

  • page/index.vue
<script lang="ts" src="./index.ts" />
<template>
  <div>
    <FormList
      class="register-info-form"
      ref="userSearchFormRef"
      :fields="userSearchFormEntity.formFields"
      :formData="userSearchFormEntity.formData"
      :rules="userSearchFormEntity.formRules"
      labelWidth="120px"
    />
  </div>
</template>

<style scoped lang="less"></style>


总结

如有启发,可点赞收藏哟~

### Vue3 和 Element-Plus 结合使用的表单示例 以下是基于 Vue3 和 Element-Plus表单验证实现方法,涵盖了基本配置以及动态校验逻辑。 #### 基本表单结构 通过 `el-form` 组件可以创建一个带有验证功能的表单。该组件支持嵌套字段、自定义规则等功能[^1]。 ```vue <template> <el-form :model="form" :rules="rules" ref="ruleFormRef"> <!-- 用户名输入框 --> <el-form-item label="用户名" prop="username"> <el-input v-model="form.username"></el-input> </el-form-item> <!-- 密码输入框 --> <el-form-item label="密码" prop="password"> <el-input type="password" v-model="form.password"></el-input> </el-form-item> <!-- 提交按钮 --> <el-form-item> <el-button type="primary" @click="submitForm">提交</el-button> </el-form-item> </el-form> </template> ``` #### 数据模型与验证规则 在脚本部分定义数据模型和对应的验证规则: ```javascript <script setup> import { reactive, ref } from 'vue'; import { ElMessage } from 'element-plus'; const form = reactive({ username: '', password: '' }); // 定义验证规则 const rules = { username: [ { required: true, message: '请输入用户名', trigger: 'blur' }, { min: 3, max: 10, message: '长度应在 3 到 10 字符之间', trigger: 'blur' } ], password: [ { required: true, message: '请输入密码', trigger: 'blur' }, { min: 6, message: '密码至少为 6 位字符', trigger: 'blur' } ] }; // 获取 el-form 实例 const ruleFormRef = ref(null); // 提交函数 const submitForm = () => { if (!ruleFormRef.value) return; ruleFormRef.value.validate((valid) => { if (valid) { ElMessage.success('表单验证成功'); } else { ElMessage.error('请修正错误后再提交'); } }); }; </script> ``` 上述代码展示了如何设置简单的表单项及其验证规则,并提供了一个触发验证的方法[^2]。 #### 动态表单扩展 对于更复杂的场景(如动态增减表单项),可以通过数组绑定的方式管理多个子项的数据源。例如,在表格中添加多条记录并逐一验证其合法性[^3]。 ```vue <template> <el-table :data="tableData" border stripe> <el-table-column label="操作"> <template #default="{ row, $index }"> <el-form-item :prop="'tableData.'+$index+'.value'" :rules="rowRules"> <el-input v-model.number="row.value"></el-input> </el-form-item> </template> </el-table-column> </el-table> </template> ``` 以上片段说明了如何将表单验证集成到表格单元格内,从而满足复杂业务需求。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值