一文教你如何用Vue+Element轻松搞定表单封装!

发布时间:2024年01月11日

一、新建FormComponent.vue

1.梳理思路,form表单有各种类型,常见的有input、select,radio,checkbox,time,date,date-picker,textarea,rate

<template>
  <el-form ref="form" :model="formData" label-width="80px">
    <el-form-item
      v-for="item in formList"
      :key="item.prop"
      :label="item.label"
      :prop="item.prop"
    >
      <div class="form-item-container">
        <template v-if="item.prefix">
          <span class="prefix">{{ item.prefix }}</span>  --前置单位
        </template>
        <template v-if="item.type === 'input'">
          <el-input
            v-model="formData[item.prop]"
            :placeholder="item.placeholder"
            :clearable="item.clearable"
            :maxlength="item.maxlength"
            @change="handleChange(item.prop, formData[item.prop])"
          />
        </template>
        <template v-if="item.type === 'textarea'">
          <el-input
            type="textarea"
            v-model="formData[item.prop]"
            :placeholder="item.placeholder"
            :clearable="item.clearable"
            :maxlength="item.maxlength"
            @change="handleChange(item.prop, formData[item.prop])"
          />
        </template>
        <template v-if="item.type === 'select'">
          <el-select
            v-model="formData[item.prop]"
            :placeholder="item.placeholder"
            :clearable="item.clearable"
            @change="handleChange(item.prop, formData[item.prop])"
          >
            <el-option
              v-for="option in item.options"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </template>
        <!-- 其它表单项同理 -->
        <template v-if="item.suffix">
          <span class="suffix">{{ item.suffix }}</span>  --后置
        </template>
      </div>
      <div class="form-item-unit" v-if="item.unit">{{ item.unit }}</div> --单位
    </el-form-item>
    <div class="form-body" v-if="!$slots.default">
      <slot></slot>
    </div>
    <div class="form-footer" v-if="$slots.footer">
      <slot name="footer"></slot>
    </div>
    <div class="form-footer" v-else>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" v-if="showSubmitButton">提交</el-button>
        <el-button @click="onCancel" v-if="showCancelButton">取消</el-button>
      </el-form-item>
    </div>
  </el-form>
</template>

<script>
export default {
  props: {
    formList: {
      type: Array,
      required: true,
    },
    formData: {
      type: Object,
      default: () => ({}),
    },
    actionUrl: {
      type: String,
      required: true,
    },
    showSubmitButton: {
      type: Boolean,
      default: true,
    },
    showCancelButton: {
      type: Boolean,
      default: true,
    },
  },
  methods: {
    handleChange(prop, value) {
      this.$emit('update:formData', {
        ...this.formData,
        [prop]: value,
      });
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$axios.post(this.actionUrl, this.formData).then((res) => {
            this.$emit('submit-success', res);//回调
          });
        } else {
          this.$message.error('请检查表单是否填写正确');
        }
      });
    },
    onCancel() {
      this.$emit('cancel');
    },
  },
};
</script>

<style>
.form-item-container {
  position: relative;
  display: inline-block;
}

.prefix,
.suffix {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  font-size: 14px;
}

.prefix {
  left: 8px;
}

.suffix {
  right: 8px;
}

.form-item-unit {
  display: inline-block;
  margin-left: 8px;
  color: #909399;
}

.form-body {
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 20px;
}

.form-footer {
  text-align: right;
  margin-top: 20px;
}
</style>

二、如何使用

引入import formComponent from 'xx';

<template>
  <div>
    <form-component
      :form-list="formList"
      :form-data="formData"
      :action-url="actionUrl"
      :show-submit-button="true"
      :show-cancel-button="true"
      @submit-success="onSubmitSuccess"
      @cancel="onCustomCancel"
      >
      <!-- 自定义表单内容 -->
      <template #default>
        <el-form-item>
          <el-radio-group v-model="formData.gender">
            <el-radio label="male">男性</el-radio>
            <el-radio label="female">女性</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-cascader
            v-model="formData.address"
            :options="addressOptions"
            placeholder="请选择地址"
            @change="handleChange('address', formData['address'])"
          />
        </el-form-item>

        <el-form-item>
          <el-input
            v-model="formData.email"
            placeholder="请输入电子邮箱"
            clearable
            @change="handleChange('email', formData['email'])"
          />
        </el-form-item>
      </template>

      <!-- 自定义底部按钮,也可以不添加,使用默认底部按钮 -->
      <template #footer>
        <el-button type="primary" @click="onCustomSubmit">提交</el-button>
        <el-button @click="onCustomCancel">取消</el-button>
      </template>
    </form-component>
  </div>
</template>

<script>
import FormComponent from './FormComponent.vue';

export default {
  components: {
    FormComponent,
  },
  data() {
    return {
      formList: [
        {
          label: '姓名',
          prop: 'name',
          type: 'input',
          placeholder: '请输入姓名',
          clearable: true,
          maxlength: 20,
        },
        {
          label: '性别',
          prop: 'gender',
          type: 'select',
          placeholder: '请选择性别',
          clearable: true,
          options: [
            {
              label: '男性',
              value: 'male',
            },
            {
              label: '女性',
              value: 'female',
            },
          ],
        },
        {
          label: '地址',
          prop: 'address',
          type: 'cascader',
          placeholder: '请选择地址',
          clearable: true,
          options: [],
        },
        {
          label: '电子邮箱',
          prop: 'email',
          type: 'input',
          placeholder: '请输入电子邮箱',
          clearable: true,
          maxlength: 50,
        },
      ],
      formData: {
        name: '',
        gender: '',
        address: [],
        email: '',
      },
      addressOptions: [
        {
          value: 'beijing',
          label: '北京',
          children: [
            {
              value: 'haidian',
              label: '海淀区',
              children: [
                {
                  value: 'zizhuqiao',
                  label: '紫竹桥',
                },
                {
                  value: 'xizhimen',
                  label: '西直门',
                },
              ],
            },
            {
              value: 'chaoyang',
              label: '朝阳区',
              children: [
                {
                  value: 'guomao',
                  label: '国贸',
                },
                {
                  value: 'cbd',
                  label: 'CBD',
                },
              ],
            },
          ],
        },
        {
          value: 'shanghai',
          label: '上海',
          children: [
            {
              value: 'xuhui',
              label: '徐汇区',
              children: [
                {
                  value: 'xujiahui',
                  label: '徐家汇',
                },
              ],
            },
            {
              value: 'pudong',
              label: '浦东新区',
              children: [
                {
                  value: 'lujiazui',
                  label: '陆家嘴',
                },
              ],
            },
          ],
        },
      ],
      actionUrl: '/api/submit-form',
    };
  },
  methods: {
    onCustomSubmit() {
      // 自定义提交按钮的点击事件
    },
    onCustomCancel() {
      // 自定义取消按钮的点击事件
    },
    onSubmitSuccess(res) {
      // 表单提交成功的回调函数
    },
  },
};
</script>

完整附件:点此下载

文章来源:https://blog.csdn.net/CRMEB/article/details/135532201
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。