ant|ant design vue的form表单取值方法
目录
- ant design vue的form表单取值
- 官方中有以下两种取值方式
- ant design of vue 学习之表单form
- v-decorator(表单验证,内置绑定,初始值)
- 数据获取与填充
- 表单实例
ant design vue的form表单取值
官方中有以下两种取值方式
文章图片
因为不是很熟悉,所以还是查了文档找了一下使用方式,刚开始查到的文档是这样写的
文章图片
然后返回了undefined,后来又查询了一些文档,发现我多加了一个props属性,然后使用第二个方法成功了,代码如下:
文章图片
ant design of vue 学习之表单form
v-decorator(表单验证,内置绑定,初始值)
1、可通过 v-decorator 进行表单验证
//内置验证规则//自定义验证规则01//自定义验证规则02
//在methods中设定方法// 手机号验证MobileNumberValidator (rule, value, callback) {const idcardReg = /^1(3|4|5|6|7|8|9)\d{9}$/if (!idcardReg.test(value)) {// eslint-disable-next-line standard/no-callback-literalcallback('非法格式')}// Note: 必须总是返回一个 callback,否则 validateFieldsAndScroll 无法响应callback()}
【ant|ant design vue的form表单取值方法】2、可通过 v-decorator 进行内置的双向绑定(详情可看下文的数据获取与填充)
数据填充(所有项)this.form.setFieldsValue(data)数据获取(所有项)this.form.validateFields(async (errors, values) => {console.log(values)});
3、可通过 v-decorator 的initialValue设置初始值
4、下拉选择框的 labelInValue 属性
通常情况下,通过this.form.getFieldValue(“courseTeacherList”),你只能获取一个数组包含value值,形如[‘7’,‘10’],而通过labelInValue属性可以得到[{key: “7”,label: “王凤”},{{key: “10”,label: “姚峰”}}]
key
表示valuelabel
表示显示值
{{ item.name }}
5、type类型检验
Typestring: Must be of type string. This is the default type.number: Must be of type number.boolean: Must be of type boolean.method: Must be of type function.regexp: Must be an instance of RegExp or a string that does not generate an exception when creating a new RegExp.integer: Must be of type number and an integer.float: Must be of type number and a floating point number.array: Must be an array as determined by Array.isArray.object: Must be of type object and not Array.isArray.enum: Value must exist in the enum.date: Value must be valid as determined by Dateurl: Must be of type url.hex: Must be of type hex.email: Must be of type email.any: Can be any type.
数据获取与填充
//获取一个输入控件的值Function(fieldName: string)let myDate = this.form.getFieldValue("startDate"); //获取一组输入控件的值,如不传入参数,则获取全部组件的值Function([fieldNames: string[]])let value = https://www.it610.com/article/this.form.getFieldsValue(["startDate","endDate"]); let value = https://www.it610.com/article/this.form.getFieldsValue(); //设置一组输入控件的值this.form.setFieldsValue({ startDate:res.result["startDate"], endDate:res.result["endDate"],})//设置一组输入控件的值加了labelInValue属性this.form.setFieldsValue({ userName:{label:res.result["userName"],key:res.result["userNameId"] }})//设置表单数据对日期、下拉框含labelInValue属性的form控件的数据设置要特殊处理才能绑定//对于日期控件需要将string类型的数据转换moment类型//对于下拉框含labelInValue属性控件,数据需要转换成key、label的对象格式import moment from 'moment'setFormValues (record) {// 控制教师if (courseTeacherList && courseTeacherList.length > 0) {record['courseTeacherList'] = courseTeacherList.map(item => ({key: item.teacherId + '',label: item.teacherName}))}const fields = ['courseTeacherList', 'certificateNo', 'cardTime', 'termValidity', 'documentStatus', 'remark']Object.keys(record).forEach((key) => {if (fields.indexOf(key) !== -1) {this.form.getFieldDecorator(key)const obj = {}if (key === 'cardTime' && record['cardTime'] != undefined) {obj[key] = moment(data[key], 'YYYY-MM-DD')} else {obj[key] = record[key]}this.form.setFieldsValue(obj)}})},//关闭表单清空表单数据this.form.resetFields(); //提交表单获取数据//通过this.form.validateFields函数进行表单验证以及数据获取//对于日期控件,获取的是moment类型数据,需要转换成字符串储存,//形如values.birthday = values.birthday ? values.birthday.format('YYYY-MM-DD') : ''handleSubmit () {const { id } = thisthis.form.validateFields((err, values) => {if (!err) {this.submitLoading = truevalues.birthday = values.birthday ? values.birthday.format('YYYY-MM-DD') : ''// 处理教师values.courseTeacherList = values.courseTeacherList.map(item => {const obj = {}obj.teacherId = Number(item.key)return obj})if (id) {// 修改updateCourse({ id, ...values }).then(res => {if (res.code == 0) {this.$message.success('保存成功')this.form.resetFields()this.$router.back()} else {this.$message.error('保存失败,请稍后再试')}}).finally(() => {this.submitLoading = false})} else {// 添加addCourse(values).then(res => {if (res.code == 0) {this.$message.success('保存成功')this.form.resetFields()this.$router.back()} else {this.$message.error('保存失败,请稍后再试')}}).finally(() => {this.submitLoading = false})}}})},
表单实例
{{ item.name }}发布不发布保存返回
import moment from 'moment'import { addCourse, getTeacherList, getCourseById, updateCourse } from '@/api/learning/course'export default {data () {return {submitLoading: false,form: this.$form.createForm(this),formItemLayout: {labelCol: {lg: { span: 7 },sm: { span: 7 }},wrapperCol: {lg: { span: 10 },sm: { span: 17 }}},teacherList: [],unitSn: ''}},created () {// 获取教师列表this.getTeacherList()// 获取详情if (this.id) {this.getInfo()}},computed: {id () {return this.$route.query.id}},methods: {// 获取教师列表getTeacherList () {const unitSn = this.unitSn || this.$store.getters.userInfo.unitSnconst params = {current: 1,size: -1,unitSn}getTeacherList(params).then(res => {if (res.code == 0) {if (res.data.records.length > 0) {this.teacherList = res.data.records.map(item => {const obj = {}obj.id = item.id + ''obj.name = item.namereturn obj})}} else {this.$message.error(res.message)}})},// 获取详情 设置表单数据getInfo () {let { id } = thisid = Number(id)getCourseById(id).then(res => {if (res.code == 0) {this.setFormValues({ ...res.data })} else {this.$message.error(res.message)}})},// 设置表单数据setFormValues (record) {const { courseTeacherList, unitSn } = recordthis.unitSn = unitSn// 控制教师if (courseTeacherList && courseTeacherList.length > 0) {record['courseTeacherList'] = courseTeacherList.map(item => ({key: item.teacherId + '',label: item.teacherName}))}const fields = ['name', 'courseTeacherList', 'introduction', 'timeLength', 'startDate', 'online', 'publish']Object.keys(record).forEach(key => {if (fields.indexOf(key) !== -1) {this.form.getFieldDecorator(key)const obj = {}if (key === 'startDate' && record['startDate'] != undefined) {obj[key] = moment(record[key], 'YYYY-MM-DD')} else {obj[key] = record[key]}this.form.setFieldsValue(obj)}})},// 保存handleSubmit () {this.form.validateFields((err, values) => {if (!err) {const { id } = thisthis.submitLoading = true// 处理教师values.courseTeacherList = values.courseTeacherList.map(item => {const obj = {}obj.teacherId = Number(item.key)return obj})// 处理日期values.startDate = values.startDate ? values.startDate.format('YYYY-MM-DD') : ''if (id) {// 修改updateCourse({ id, ...values }).then(res => {if (res.code == 0) {this.$message.success('保存成功')this.form.resetFields()this.$router.back()} else {this.$message.error('保存失败,请稍后再试')}}).finally(() => {this.submitLoading = false})} else {// 添加addCourse(values).then(res => {if (res.code == 0) {this.$message.success('保存成功')this.form.resetFields()this.$router.back()} else {this.$message.error('保存失败,请稍后再试')}}).finally(() => {this.submitLoading = false})}}})},// 返回back () {this.$confirm({title: '还未保存,是否返回上一级?',okText: '确认返回',cancelText: '取消',onOk: () => {this.$router.back()}})}}}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
推荐阅读
- Vue3|Vue3 优雅的模态框封装方案
- 面试官: 有了解过ReentrantLock的底层实现吗(说说看)
- 数字资产知识库管理系统实现过程(springboot+es+vue+neo4j)
- VUE|vue项目中 localStorage 的用法建议
- VUE|vue 实现点击“增加“”按钮,添加一个HTML元素
- VUE|Vue项目(style样式篇)
- VUE|vue使用xe-utils通用函数库
- Vue动画效果
- electron-vue|electron-vue 项目启动动态获取配置文件中的后端服务地址
- 结合项目带你了解,Vue组件重复利用,及父组件传递数据给子组件