vue移动端form表单组件封装

3,340 阅读2分钟

在一次项目中使用vant-ui写表单时,觉得组件之间的调用比较繁琐,当我页面中的表单比较多的情况下,就有点不好维护了,当遇见下图中的表单,我崩溃了🌝,这种表单在项目中有很多,需要自己处理组件间的数据逻辑、校验等。

需求

针对上边的举例,我将vant-ui的表单组件做了一层封装,方便对表单的处理,目前已有功能如下:

  1. 目前已经集成输入框、数字输入框、单选框、复选框、时间选择器、地址选择器、下拉选择框、开关按扭、纯文字展示、文件上传、验证码组件,组件不满足的情况支持二开引入组件;
  2. 组件采用 JSON 配置形式调用组件;
  3. 内置集成繁琐的校验功能,使用组件可以不用考虑校验问题,校验规则也可以自定义扩展,同时满足关联表单校验;
  4. 不需要自己手写组件之间的数据依赖,组件内部处理好数据,统一对外暴露。

配置参数示例

const model = {
  // 以下三个文字输入示例为关联校验
  // 关联校验采取{rule}:@{field},@{field}格式
  // 接收字段采取@{rule}格式
  text1: {
    value: '',
    rules: {
      label: '文字1',
      type: 'VInput',
      vRules: 'required|custom:@text2,@text3',
      placeholder: '请输入文字',
      errMsg: '请输入文字'
    }
  },

  text2: {
    value: '',
    rules: {
      label: '文字2',
      type: 'VInput',
      vRules: 'required|@custom',
      placeholder: '请输入文字',
      errMsg: '请输入文字'
    }
  },

  text3: {
    value: '',
    rules: {
      label: '文字3',
      type: 'VInput',
      vRules: 'required|@custom',
      placeholder: '请输入文字',
      errMsg: '请输入文字'
    }
  },

  // 时间选择器
  date: {
    value: Date.now(),
    rules: {
      label: '时间',
      // 共4种类型:datetime、year-month、date、time
      type: 'VDatePicker|datetime',
      // 数据格式处理:timestamp时间戳,其他用法参考:https://github.com/xuanmos/datejs
      valueFormat: 'yyyy-MM-dd'
    }
  },

  // 图片上传
  file: {
    // 用于显示列表
    value: [{ path: 'https://upyun.xuanmo.xin/test/20200418225229.png' }],
    rules: {
      label: '文件上传',
      type: 'VUpload',
      action: 'xxx',
      accept: 'image/png',
      multiple: true,
      name: 'file',
      headers: {},
      // 上传附加的数据
      data: {
        dir: 'test'
      },
      // 自定义配置项,用于指定url字段为某个属性值
      props: {
        url: 'path'
      }
    }
  }
}

组件具体使用说明:github.com/D-xuanmo/v-…

Github仓库:github.com/D-xuanmo/v-…

Npm地址:www.npmjs.com/package/@xu…

在线预览可编辑(PC端):codesandbox.io/s/v-formshi…

在线预览:assets.xuanmo.xin/v-form