Skip to content

Form 表单

基本使用

template
<c-form>
  <c-form-item label="账号">
    <c-input placeholder="用户名" />
  </c-form-item>
</c-form>

验证规则

添加对 trigger 支持; 值有: 'input' 、 'change' 、 'blur' 和 'focus' 。

其它参数详情请查看 async-validator

ts
import type { FormRules, RadioProps } from '@/uni_modules/cfg-design'
import { ref } from 'vue'
import CForm from '@/uni_modules/cfg-design/components/c-form/c-form.vue'
import Form1 from './form1.vue'

const defaultFormData = {
  nickName: '',
  name: 'user0',
  pass: '',
  pass2: '',
  brief: '',
  hobby: [],
  agreement: false,
  sex: '',
  sync: false,
  age: 17
}

const sexs: RadioProps[] = [
  { text: '', value: '1' },
  { text: '', value: '2' },
  { text: '保密[no-feedback]', value: '3', noFeedback: true }
]

const formRef = ref<InstanceType<typeof CForm>>()
const formData = ref({ ...defaultFormData })
const rules: FormRules = {
  name: [
    {
      required: true,
      message: '用户名不能为空',
      trigger: 'input'
    }
  ],
  pass: [
    {
      required: true,
      message: '密码不能为空',
      trigger: ['input']
    }
  ],
  pass2: [
    {
      required: true,
      message: '密码2不能为空',
      trigger: ['input', 'blur']
    },
    {
      // 小程序不支持方法传参。需要使用 formRef.value!.setRules(rules) 来设置
      validator: () => formData.value.pass === formData.value.pass2,
      message: '两次密码输入不同',
      trigger: 'blur'
    },
  ],
  hobby: [
    {
      required: true,
      type: 'array',
      message: '请选择你的爱好',
      trigger: 'change'
    }
  ],
  sex: [
    {
      required: true,
      message: '请选择性别',
      trigger: ['change']
    }
  ],
  brief: [
    {
      required: true,
      message: '简介不能为空',
      trigger: 'input'
    }
  ],
  agreement: [
    {
      required: true,
      type: 'enum',
      enum: [true],
      message: '请选择阅读并同意协议',
      trigger: 'change'
    }
  ],
  sync: [
    {
      required: true,
      type: 'enum',
      enum: [true],
      message: '请开启同步',
      trigger: 'change'
    }
  ],
  age: [
    {
      required: true,
      type: 'number',
      min: 18,
      message: '年龄太小',
      trigger: 'change'
    }
  ],
}

const onSubmit = () => {
  formRef.value?.validate((errors) => {
    console.log(errors)
    if (errors) {
      uni.showToast({
        title: errors[0].message,
        icon: 'error'
      })
      return
    }

    uni.showToast({ title: 'submitting' })
  })
}
const onReset = () => formRef.value!.reset()
const clear = () => formRef.value!.clear()
const restoreValidation = () => formRef.value!.restoreValidation()
template
<c-form
  ref="formRef"
  v-model:value="formData"
  :rules="rules"
  :item="{ labelWidth: 120 }"
>
  <c-form-item no-label no-border-bottom>
    <c-row gutter="10rpx">
      <c-col>
        <c-button color="warning" text="清空校验结果" width="100%" @click="restoreValidation" />
      </c-col>
      <c-col>
        <c-button color="success" text="清空数据" width="100%" @click="clear" />
      </c-col>
      <c-col>
        <c-button color="error" text="重置" width="100%" form-type="reset" @click="onReset" />
      </c-col>
      <c-col>
        <c-button color="primary" text="提交" width="100%" form-type="submit" @click="onSubmit" />
      </c-col>
    </c-row>
  </c-form-item>
  <c-form-item label="昵称">
    <c-input v-model:value="formData.nickName" placeholder="昵称" />
  </c-form-item>
  <c-form-item label="账号" path="name">
    <c-input v-model:value="formData.name" placeholder="用户名" clearable />
  </c-form-item>
  <c-form-item label="密码" path="pass">
    <c-input v-model:value="formData.pass" password placeholder="密码" auto-focus clearable />
  </c-form-item>
  <c-form-item label="密码2" path="pass2">
    <c-input v-model:value="formData.pass2" password placeholder="再次输入密码" border />
  </c-form-item>
  <c-form-item label="密码2" path="pass2">
    <c-input v-model:value="formData.pass2" password placeholder="input: no-feedback" border no-feedback />
  </c-form-item>
  <c-form-item label="密码2" path="pass2" no-feedback>
    <c-input v-model:value="formData.pass2" password placeholder="form-item: no-feedback" border />
  </c-form-item>
  <c-form-item label="爱好" path="hobby">
    <c-checkbox-group v-model:value="formData.hobby" c="row">
      <c-checkbox text="看电影" />
      <c-checkbox text="听音乐[no-feedback]" no-feedback />
    </c-checkbox-group>
  </c-form-item>
  <c-form-item label="性别" path="sex">
    <c-radio-group v-model:value="formData.sex" c="row" :items="sexs" />
  </c-form-item>
  <c-form-item label="同步" path="sync">
    <c-switch v-model:value="formData.sync" round />
    <c-switch v-model:value="formData.sync" no-feedback un-checked-text="no-feedback" checked-text="no-feedback" />
  </c-form-item>
  <c-form-item label="年龄" path="age">
    <c-input-number v-model:value="formData.age" />
  </c-form-item>
  <c-form-item label="简介" path="brief">
    <c-textarea v-model:value="formData.brief" placeholder="简介" height="100rpx" />
  </c-form-item>
  <c-form-item label="协议" path="agreement">
    <c-checkbox v-model:checked="formData.agreement">
      <c-text>已阅读并同意</c-text><c-text color="primary" @click.stop="">《xxxxxxxxxx》</c-text><c-text>协议</c-text>
    </c-checkbox>
  </c-form-item>
</c-form>

API

Form Props

名称类型默认值版本说明
cstringdefault配置名。使用说明
propsFormPropsundefined全部 props 。 使用说明
c-classHTMLAttributes['class']undefined自定义类名
c-styleHTMLAttributes['style']undefined自定义样式
valueRecord<string, any>undefined表单数据对象
rulesFormRulesundefined验证规则async-validator
disabledbooleanundefined是否禁用
itemFormItemPropsundefinedFormItemProps

FormItem Props

名称类型默认值版本说明
cstringdefault配置名。使用说明
propsFormPropsundefined全部 props 。 使用说明
c-classHTMLAttributes['class']undefined自定义类名
c-styleHTMLAttributes['style']undefined自定义样式
main-classHTMLAttributes['class']undefinedmain 的自定义类名
main-styleHTMLAttributes['style']undefinedmain 的自定义样式
label-classHTMLAttributes['class']undefinedlabel 的自定义类名
label-styleHTMLAttributes['style']undefinedlabel 的自定义样式
content-classHTMLAttributes['class']undefinedcontent 的自定义类名
content-styleHTMLAttributes['style']undefinedcontent 的自定义样式
sizestring | numberundefined字体大小。 使用说明
pathstringundefinedCForm value 对象的属性名,用于校验
labelstringundefined标签文字
label-placement'left' | 'top'undefined标签显示的位置
label-widthstring | numberundefined标签的宽度
label-forstringundefined绑定控件的 id
label-text-propsTextPropsundefined标签文字。TextProps
right-iconstringundefined右边图标名称或代码
right-icon-propsIconPropsundefinedIconProps
error-propsTextPropsundefinedTextProps
disabledbooleanundefined是否禁用
no-feedbackbooleanundefined是否不展示校验反馈
no-labelbooleanundefined是否展示标签
no-require-markbooleanundefined是否展示必填的星号
no-border-bottombooleanundefined是否不显示表单项的下划线边框
line-propsLinePropsundefined下划线边框。LineProps

FormItem Slots

名称参数说明
default()自定义 content 左边的内容
label()自定义 label
error({ errMsg: string | undefined })自定义错误提示

Form Methods

名称类型说明
setRules(rules: FormRules) => void设置验证规则。用来解决小程序 props 不能传方法问题。
validate(callback?: (errors: ValidateError[] | null, fields: ValidateFieldsError | Values) => void) => Promise<Values>验证表单
validateField(field: string, callback?: ValidateCallback, trigger?: ValidationTrigger) => Promise<Values>对表单某个字段进行验证。 callback 同跟 validate 一样
restoreValidation() => void清空校验结果
clear() => void删除表单数据,并清空校验结果
reset() => void还原表单数据,并清空校验结果

Form Events

名称参数说明
submit(event: any) => void携带 form 中的数据触发 submit 事件,event.detail = {value : {'name': 'value'} , formId: ''},report-submit 为 true 时才会返回 formId
reset(event: any) => void表单重置时会触发 reset 事件
update:value(value: FormProps['value']) => voidvalue change 时触发

Form Provides

ts
import {
  formInjectionKeyDisabled,
  formInjectionKeyFieldsErrors,
  formInjectionKeyItemProps,
  formInjectionKeyRules,
  formInjectionKeyValidateField
} from '@/uni_modules/cfg-design'
名称类型说明
formInjectionKeyRulesInjectionKey<Ref<FormRules>> = Symbol()验证规则
formInjectionKeyDisabledInjectionKey<Ref<boolean>> = Symbol()是否禁用
formInjectionKeyItemPropsInjectionKey<Ref<FormItemProps>> = Symbol()FormItemProps
formInjectionKeyFieldsErrorsInjectionKey<Ref<ValidateFieldsError>> = Symbol()验证错误结果数据
formInjectionKeyValidateFieldInjectionKey<FormValidateField> = Symbol()对表单某个字段进行验证, 跟 Methods validateField 相同

FormItem Provides

ts
import {
  formItemInjectionKeyDisabled,
  formItemInjectionKeyNoFeedback,
  formItemInjectionKeyPath,
  formItemInjectionKeySize
} from '@/uni_modules/cfg-design'
名称类型说明
formItemInjectionKeySizeInjectionKey<Ref<string>> = Symbol()字体大小
formItemInjectionKeyDisabledInjectionKey<Ref<boolean>> = Symbol()是否禁用
formItemInjectionKeyPathInjectionKey<Ref<string>> = Symbol()CForm value 对象的属性名,用于校验
formItemInjectionKeyNoFeedbackInjectionKey<Ref<boolean>> = Symbol()是否不展示校验反馈