AntDesign vue学习笔记,七Form 读写与图片上传

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) {

this.form.getFieldValue("username");

注:此处也可以直接拿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 }

(二)上传图片

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,就需要使用其他写法,请看笔记九。

AntDesign vue学习笔记(九)自定义文件上传