您好,登錄后才能下訂單哦!
本篇內容介紹了“ant design vue的form表單如何取值”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
因為不是很熟悉,所以還是查了文檔找了一下使用方式,剛開始查到的文檔是這樣寫的
然后返回了undefined,后來又查詢了一些文檔,發現我多加了一個props屬性,然后使用第二個方法成功了,代碼如下:
1、可通過 v-decorator 進行表單驗證
//內置驗證規則 <a-form-item label="課程名稱" v-bind="formItemLayout"> <a-input placeholder="課程名稱" v-decorator="['name', { rules: [{ required: true, max: 50, message: '必填項,最大50字符' }] }]" /> </a-form-item> //自定義驗證規則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> //自定義驗證規則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中設定方法 // 手機號驗證 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 無法響應 callback() }
2、可通過 v-decorator 進行內置的雙向綁定(詳情可看下文的數據獲取與填充)
數據填充(所有項) this.form.setFieldsValue(data) 數據獲取(所有項) this.form.validateFields(async (errors, values) => { console.log(values) });
3、可通過 v-decorator 的initialValue設置初始值
<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”),你只能獲取一個數組包含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"); //獲取一組輸入控件的值,如不傳入參數,則獲取全部組件的值 Function([fieldNames: string[]]) let value = this.form.getFieldsValue(["startDate","endDate"]); let value = 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 } = 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> <!-- 開關滑塊 --> <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="是否發布" v-bind="formItemLayout"> <a-radio-group name="radioGroup" v-decorator="['publish', { initialValue: 1 }]"> <a-radio :value="1">發布</a-radio> <a-radio :value="0">不發布</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) } }) }, // 獲取詳情 設置表單數據 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) } }) }, // 設置表單數據 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: '確認返回', cancelText: '取消', onOk: () => { this.$router.back() } }) } } } </script> <style lang="less" scoped></style>
“ant design vue的form表單如何取值”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。