ant?design?vue的form表單取值方法
ant design vue的form表單取值
官方中有以下兩種取值方式

因?yàn)椴皇呛苁煜ぃ赃€是查了文檔找了一下使用方式,剛開始查到的文檔是這樣寫的
![]()
然后返回了undefined,后來又查詢了一些文檔,發(fā)現(xiàn)我多加了一個(gè)props屬性,然后使用第二個(gè)方法成功了,代碼如下:
![]()
ant design of vue 學(xué)習(xí)之表單form
v-decorator(表單驗(yàn)證,內(nèi)置綁定,初始值)
1、可通過 v-decorator 進(jìn)行表單驗(yàn)證
//內(nèi)置驗(yàn)證規(guī)則
<a-form-item label="課程名稱"
? ? ? ? ? ? ?v-bind="formItemLayout">
? ?<a-input placeholder="課程名稱"
? ? ? ? ? ? v-decorator="['name', { rules: [{ required: true, max: 50, message: '必填項(xiàng),最大50字符' }] }]" />
</a-form-item>
//自定義驗(yàn)證規(guī)則01
<a-form-item>
? <a-input size="large"
? ? ? ? ? ?type="text"
? ? ? ? ? ?placeholder="手機(jī)號(hào)"
? ? ? ? ? ?v-decorator="['mobileNumber',?
? ? ? ? ? ?{rules: [{ required: true, pattern: /^1[34578]\d{9}$/, message: '請(qǐng)輸入正確的手機(jī)號(hào)' }], validateTrigger: 'change'}]">
? ? <a-icon slot="prefix"
? ? ? ? ? ? type="mobile"
? ? ? ? ? ? :style="{ color: 'rgba(0,0,0,.25)' }" />
? </a-input>
</a-form-item>
//自定義驗(yàn)證規(guī)則02
<a-form-item ? v-bind="formItemLayout"
?? ? ? ? ? ? ? label="手機(jī)號(hào)碼">
?? ? <a-input placeholder="手機(jī)號(hào)碼"
?? ? ? ? ? ? ?v-decorator="['mobileNumber',{rules: [{ required: true,max:11,message:'請(qǐng)輸入正確格式的手機(jī)號(hào)碼',validator:MobileNumberValidator}]}]" />
</a-form-item>//在methods中設(shè)定方法
// 手機(jī)號(hào)驗(yàn)證
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: 必須總是返回一個(gè) callback,否則 validateFieldsAndScroll 無法響應(yīng)
? callback()
}
2、可通過 v-decorator 進(jìn)行內(nèi)置的雙向綁定(詳情可看下文的數(shù)據(jù)獲取與填充)
數(shù)據(jù)填充(所有項(xiàng)) ? this.form.setFieldsValue(data)
數(shù)據(jù)獲取(所有項(xiàng)) ? 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: '必填項(xiàng),最大50字符' }] }]" />
</a-form-item>4、下拉選擇框的 labelInValue 屬性
通常情況下,通過this.form.getFieldValue(“courseTeacherList”),你只能獲取一個(gè)數(shù)組包含value值,形如[‘7’,‘10’],而通過labelInValue屬性可以得到[{key: “7”,label: “王鳳”},{{key: “10”,label: “姚峰”}}]
key表示valuelabel表示顯示值
<a-form-item label="教師"
v-bind="formItemLayout">
<a-select mode="multiple"
labelInValue
placeholder="請(qǐng)選擇教師"
v-decorator="['courseTeacherList', { rules: [{ required: true, message: '必填項(xiàng),請(qǐng)選擇教師' }] }]">
<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類型檢驗(yàn)
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.數(shù)據(jù)獲取與填充
//獲取一個(gè)輸入控件的值 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ù) 對(duì)日期、下拉框含labelInValue屬性的form控件的數(shù)據(jù)設(shè)置要特殊處理才能綁定
//對(duì)于日期控件需要將string類型的數(shù)據(jù)轉(zhuǎn)換moment類型
//對(duì)于下拉框含labelInValue屬性控件,數(shù)據(jù)需要轉(zhuǎn)換成key、label的對(duì)象格式
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ù)進(jìn)行表單驗(yàn)證以及數(shù)據(jù)獲取
//對(duì)于日期控件,獲取的是moment類型數(shù)據(jù),需要轉(zhuǎn)換成字符串儲(chǔ)存,
//形如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('保存失敗,請(qǐng)稍后再試')
}
}).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('保存失敗,請(qǐng)稍后再試')
}
}).finally(() => {
this.submitLoading = false
})
}
}
})
},
表單實(shí)例
<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: '必填項(xiàng),最大50字符' }] }]" />
</a-form-item>
<a-form-item label="教師"
v-bind="formItemLayout">
<a-select mode="multiple"
labelInValue
placeholder="請(qǐng)選擇教師"
v-decorator="['courseTeacherList', { rules: [{ required: true, message: '必填項(xiàng),請(qǐng)選擇教師' }] }]">
<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: '必填項(xiàng),最大1000字符' }] }]" />
</a-form-item>
<!-- 步進(jìn)器 -->
<a-form-item label="時(shí)長"
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: '請(qǐng)選擇開課日期' }] }]"
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"
style="text-align: center;">
<a-button :loading="submitLoading"
style="margin-left: 16px"
type="primary"
@click="handleSubmit">保存</a-button>
<a-button style="margin-left: 16px"
@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('保存失敗,請(qǐng)稍后再試')
}
}).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('保存失敗,請(qǐng)稍后再試')
}
}).finally(() => {
this.submitLoading = false
})
}
}
})
},
// 返回
back () {
this.$confirm({
title: '還未保存,是否返回上一級(jí)?',
okText: '確認(rèn)返回',
cancelText: '取消',
onOk: () => {
this.$router.back()
}
})
}
}
}
</script>
<style lang="less" scoped></style>
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解vue項(xiàng)目中調(diào)用百度地圖API使用方法
這篇文章主要介紹了vue項(xiàng)目中調(diào)用百度地圖API使用方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
vue2移動(dòng)端使用vue-qrcode-reader實(shí)現(xiàn)掃一掃功能的步驟
最近在使用vue開發(fā)的h5移動(dòng)端想要實(shí)現(xiàn)一個(gè)調(diào)用攝像頭掃描二維碼的功能,所以下面這篇文章主要給大家介紹了關(guān)于vue2移動(dòng)端使用vue-qrcode-reader實(shí)現(xiàn)掃一掃功能的相關(guān)資料,需要的朋友可以參考下2023-06-06
如何構(gòu)建 vue-ssr 項(xiàng)目的方法步驟
這篇文章主要介紹了如何構(gòu)建 vue-ssr 項(xiàng)目的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
vite+vue3項(xiàng)目解決低版本兼容性問題解決方案(Safari白屏)
這篇文章主要介紹了vite+vue3項(xiàng)目解決低版本兼容性問題(Safari白屏),使用官方插件 @vitejs/plugin-legacy 為打包后的文件提供傳統(tǒng)瀏覽器兼容性支持,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2024-03-03
VUE對(duì)Storage的過期時(shí)間設(shè)置,及增刪改查方式
這篇文章主要介紹了VUE對(duì)Storage的過期時(shí)間設(shè)置,及增刪改查方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
詳解vue2父組件傳遞props異步數(shù)據(jù)到子組件的問題
本篇文章主要介紹了vue2父組件傳遞props異步數(shù)據(jù)到子組件的問題,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06
vue結(jié)合g6實(shí)現(xiàn)樹級(jí)結(jié)構(gòu)(compactBox?緊湊樹)
本文主要介紹了vue結(jié)合g6實(shí)現(xiàn)樹級(jí)結(jié)構(gòu),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
解決VMware中vmware-vmx.exe進(jìn)程無法關(guān)閉以及死機(jī)等問題
這篇文章主要介紹了解決VMware中vmware-vmx.exe進(jìn)程無法關(guān)閉以及死機(jī)等問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06
基于Vue3+element-plus實(shí)現(xiàn)中英文切換功能
在?Vue?3?項(xiàng)目中結(jié)合?vue-i18n?和?Element?Plus?實(shí)現(xiàn)中英文切換是一個(gè)常見的需求,下面是一個(gè)詳細(xì)的步驟指南,幫助你完成這個(gè)任務(wù),需要的朋友可以參考下2024-11-11

