您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“ant design vue的form表單如何取值”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
因為不是很熟悉,所以還是查了文檔找了一下使用方式,剛開始查到的文檔是這樣寫的
然后返回了undefined,后來又查詢了一些文檔,發(fā)現(xiàn)我多加了一個props屬性,然后使用第二個方法成功了,代碼如下:
1、可通過 v-decorator 進行表單驗證
//內(nèi)置驗證規(guī)則 <a-form-item label="課程名稱" v-bind="formItemLayout"> <a-input placeholder="課程名稱" v-decorator="['name', { rules: [{ required: true, max: 50, message: '必填項,最大50字符' }] }]" /> </a-form-item> //自定義驗證規(guī)則01 <a-form-item> <a-input size="large" type="text" placeholder="手機號" v-decorator="['mobileNumber', {rules: [{ required: true, pattern: /^1[34578]\d{9}$/, message: '請輸入正確的手機號' }], validateTrigger: 'change'}]"> <a-icon slot="prefix" type="mobile" : /> </a-input> </a-form-item> //自定義驗證規(guī)則02 <a-form-item v-bind="formItemLayout" label="手機號碼"> <a-input placeholder="手機號碼" v-decorator="['mobileNumber',{rules: [{ required: true,max:11,message:'請輸入正確格式的手機號碼',validator:MobileNumberValidator}]}]" /> </a-form-item>
//在methods中設(shè)定方法 // 手機號驗證 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-literal callback('非法格式') } // Note: 必須總是返回一個 callback,否則 validateFieldsAndScroll 無法響應(yīng) callback() }
2、可通過 v-decorator 進行內(nèi)置的雙向綁定(詳情可看下文的數(shù)據(jù)獲取與填充)
數(shù)據(jù)填充(所有項) this.form.setFieldsValue(data) 數(shù)據(jù)獲取(所有項) this.form.validateFields(async (errors, values) => { console.log(values) });
3、可通過 v-decorator 的initialValue設(shè)置初始值
<a-form-item label="課程名稱" v-bind="formItemLayout"> <a-input placeholder="課程名稱" v-decorator="['name', { initialValue:'姚峰', rules: [{ required: true, max: 50, message: '必填項,最大50字符' }] }]" /> </a-form-item>
4、下拉選擇框的 labelInValue 屬性
通常情況下,通過this.form.getFieldValue(“courseTeacherList”),你只能獲取一個數(shù)組包含value值,形如[‘7’,‘10’],而通過labelInValue屬性可以得到[{key: “7”,label: “王鳳”},{{key: “10”,label: “姚峰”}}]
key
表示value
label
表示顯示值
<a-form-item label="教師" v-bind="formItemLayout"> <a-select mode="multiple" labelInValue placeholder="請選擇教師" v-decorator="['courseTeacherList', { rules: [{ required: true, message: '必填項,請選擇教師' }] }]"> <a-select-option v-for="item in teacherList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option> </a-select> </a-form-item>
5、type類型檢驗
Type string: 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 Date url: 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"); //獲取一組輸入控件的值,如不傳入?yún)?shù),則獲取全部組件的值 Function([fieldNames: string[]]) let value = this.form.getFieldsValue(["startDate","endDate"]); let value = this.form.getFieldsValue(); //設(shè)置一組輸入控件的值 this.form.setFieldsValue({ startDate:res.result["startDate"], endDate:res.result["endDate"], }) //設(shè)置一組輸入控件的值 加了labelInValue屬性 this.form.setFieldsValue({ userName:{ label:res.result["userName"], key:res.result["userNameId"] } }) //設(shè)置表單數(shù)據(jù) 對日期、下拉框含labelInValue屬性的form控件的數(shù)據(jù)設(shè)置要特殊處理才能綁定 //對于日期控件需要將string類型的數(shù)據(jù)轉(zhuǎn)換moment類型 //對于下拉框含labelInValue屬性控件,數(shù)據(jù)需要轉(zhuǎn)換成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) } }) }, //關(guān)閉表單清空表單數(shù)據(jù) this.form.resetFields(); //提交表單獲取數(shù)據(jù) //通過this.form.validateFields函數(shù)進行表單驗證以及數(shù)據(jù)獲取 //對于日期控件,獲取的是moment類型數(shù)據(jù),需要轉(zhuǎn)換成字符串儲存, //形如values.birthday = values.birthday ? values.birthday.format('YYYY-MM-DD') : '' handleSubmit () { const { id } = this this.form.validateFields((err, values) => { if (!err) { this.submitLoading = true values.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 }) } } }) },
<template> <div> <a-card> <a-form :form="form"> <!-- 文本框 --> <a-form-item label="課程名稱" v-bind="formItemLayout"> <a-input placeholder="課程名稱" v-decorator="['name', { rules: [{ required: true, max: 50, message: '必填項,最大50字符' }] }]" /> </a-form-item> <a-form-item label="教師" v-bind="formItemLayout"> <a-select mode="multiple" labelInValue placeholder="請選擇教師" v-decorator="['courseTeacherList', { rules: [{ required: true, message: '必填項,請選擇教師' }] }]"> <a-select-option v-for="item in teacherList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option> </a-select> </a-form-item> <!-- 文本域 --> <a-form-item label="課程簡介" v-bind="formItemLayout"> <a-textarea placeholder="課程簡介" :autosize="{ minRows: 6, maxRows: 10 }" v-decorator="['introduction', { rules: [{ required: true, max: 1000, message: '必填項,最大1000字符' }] }]" /> </a-form-item> <!-- 步進器 --> <a-form-item label="時長" v-bind="formItemLayout"> <a-input-number v-decorator="['timeLength',{initialValue:60,rules:[{required:true,message:'必填'}]}]" :min="1" :max="100" :precision="0" /> </a-form-item> <!-- 日期控件 --> <a-form-item label="開課日期" v-bind="formItemLayout"> <a-date-picker v-decorator="['startDate', { rules: [{ type: 'object', required: true, message: '請選擇開課日期' }] }]" format="YYYY-MM-DD" /> </a-form-item> <!-- 開關(guān)滑塊 --> <a-form-item label="在線課程" v-bind="formItemLayout"> <a-switch checkedChildren="是" unCheckedChildren="否" v-decorator="['online', { valuePropName: 'checked', initialValue: true }]" /> </a-form-item> <!-- 單選框 --> <a-form-item label="是否發(fā)布" v-bind="formItemLayout"> <a-radio-group name="radioGroup" v-decorator="['publish', { initialValue: 1 }]"> <a-radio :value="1">發(fā)布</a-radio> <a-radio :value="0">不發(fā)布</a-radio> </a-radio-group> </a-form-item> </a-form> <a-row> <a-col :span="14" :offset="5" > <a-button :loading="submitLoading" type="primary" @click="handleSubmit">保存</a-button> <a-button @click="back">返回</a-button> </a-col> </a-row> </a-card> </div> </template>
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.unitSn const 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.name return obj }) } } else { this.$message.error(res.message) } }) }, // 獲取詳情 設(shè)置表單數(shù)據(jù) getInfo () { let { id } = this id = Number(id) getCourseById(id).then(res => { if (res.code == 0) { this.setFormValues({ ...res.data }) } else { this.$message.error(res.message) } }) }, // 設(shè)置表單數(shù)據(jù) setFormValues (record) { const { courseTeacherList, unitSn } = record this.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 } = this this.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: '確認(rèn)返回', cancelText: '取消', onOk: () => { this.$router.back() } }) } } } </script> <style lang="less" scoped></style>
“ant design vue的form表單如何取值”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。