AntDesign Form使用布局相比傳統Jquery有點繁瑣
(一)先讀寫一個簡單的input為例
<a-form :form="form" layout="vertical" hideRequiredMark> <a-row> <a-col :span="8"> <a-form-item label="用戶名"> <a-input v-decorator="['username', {rules: [{ required: true, message: '用戶名' }]}]" placeholder /> </a-form-item> ....
1、讀數據,很簡單
this.form.validateFields((err, values) => {
if (!err) {
注:此處也可以直接拿values中值使用
2、寫數據,根據經驗把get變成set,提示不存在setFieldValue(!-_-)
換一個
換一個
this.form.setFieldsValue('username', '測試')
執行一直不成功,提示
browser.js?1af0:49 Warning: You cannot set a form field before rendering a field associated with the value.
網上查各種資料未找到原因,通過以下方法嘗試解決
(1)this.form.getFieldDecorator('username', { initialValue: '' })無效果
(2)setTimeout無效果
(3)最終發現需要這樣寫
this.form.setFieldsValue({
'username': '測試'
})
注意正確應該多一對
{},很奇怪為啥沒有setFieldValue
函數原型:setFieldsValue Set the value of a field. Function({ [fieldName]: value }
函數原型:setFieldsValue Set the value of a field. Function({ [fieldName]: value }
(二)上傳圖片
1、data()中定義FileList,初始化圖片如下面格式(可以不初始化)
fileList: [{
uid: '-1',
name: 'xxx.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
}]
2、下面是點擊圖片后自動上傳寫法,可以將action替換為你自己的上傳圖片后台地址
<a-row> <a-col :span="12"> <a-form-item label="圖片"> <a-upload action="https://www.mocky.io/v2/5cc8019d300000980a055e76" listType="picture-card" :fileList="fileList" @preview="handlePreview" @change="handleChange" > <div v-if="fileList.length < 1"> <a-icon type="plus"/> <div class="ant-upload-text">上傳圖片</div> </div> </a-upload> </a-form-item> </a-col> </a-row>
handleCancel () { this.previewVisible = false }, handlePreview (file) { this.previewImage = file.url || file.thumbUrl this.previewVisible = true }, handleChange ({ fileList }) { this.fileList = fileList }
.ant-upload-select-picture-card i { font-size: 32px; color: #999; } .ant-upload-select-picture-card .ant-upload-text { margin-top: 8px; color: #666; }
3、當選擇圖片時已經自動調用action接口,后台返回數據如下
{
"name": "xxx.png",
"status": "done",
"url": "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png",
"thumbUrl": "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
}
4、到此時已經將圖片上傳到了服務上了,實際項目中需要同時上傳token,就需要使用其他寫法,請看筆記九。