uniapp上传图片的表单校验

用uni-forms的setValue方法

  • name: 表单域对应的name
  • value: 表单域对应的值
this.$refs.form.setValue(name,value)

html 

<uni-forms v-else ref="form" :modelValue="info" :label-width="100" :rules="rules">
  <uni-forms-item label="从业人员照片" required name="xpPath">
                <u-upload
                        :fileList="xpList"
                        @afterRead="afterReadXp"
                        @delete="deleteXp"
                        name="1"
                        :maxCount="1"
                        previewImage
                        v-model="info.xpPath"
                ></u-upload>
            </uni-forms-item>
 <u-button type="primary" text="提交" @click="submit"></u-button>
 </uni-forms>

js

图片上传完成之后,使用setValue方法,手动将图片值加入到uni-forms的校验,再次触发校验

this.$refs.form.setValue('xpPath',this.info.xpPath)

data() {
            return {
                info: {},
                rules: {
                    xpPath: {
                        rules: [{
                            required: true,
                            errorMessage: '请选择从业人员照片'
                        }]
                    },
                },
                xpList: [],
            }
        },
methods:{
             // 删除从业人员照片
            deleteXp(event) {
                this.xpList = []
            },
            // 新增从业人员照片
            async afterReadXp(e) {
                const res = await this.uploadFilePromise(e.file.url)
                this.info.xpPath = JSON.parse(res.data).data
                this.$refs.form.setValue('xpPath',this.info.xpPath)//手动将图片值加入到uni-forms的校验
                this.xpList = [{
                    url:  JSON.parse(res.data).data
                }]
            },
            uploadFilePromise(url) {
                return new Promise((resolve, reject) => {
                    let a = uni.uploadFile({
                        url: 'http://192.168.2.21:7001/upload', // 仅为示例,非真实的接口地址
                        filePath: url,
                        name: 'file',
                        formData: {
                            user: 'test'
                        },
                        success: (res) => {
                            setTimeout(() => {
                                resolve(res)
                            }, 500);
                        }
                    });
                })
            },
           submit() {
                this.$refs['form'].validate().then(res => {
                   
                }).catch(err => {

                })

}

猜你喜欢

转载自blog.csdn.net/starstarstarl/article/details/129057943