2020-09-06 form-create插件 后端表单生成上传组件在前端上传回调链接地址无法自动获取的解决办法

form-create 插件上传组件的配置文档:
http://www.form-create.com/v2/element-ui/components/upload.html
这是一个在前端模拟JSON上传组件的示例:

模拟JSON上传组件的示例

【注意点:】重点在于onSuccess()这个方法后端是不会生成出来给前端的,需要前端自己设置回调函数并对其回调参数file赋值,这样插件的表单数据才能绑定到上传结果的数据,并在提交表单的时候才能正常取到数据。官方文档没有重点说明这一点,一开始没注意看捣鼓了很久。。。

方法一:我们可以在api接口文件里进行拦截和设置上传组件的onSuccess回调函数

例如:

/**
 * @description APP版本信息 -- 编辑
 */
export async function appVersionsUpdateApi(id) {
  let res = await request.get(`mmp/appVersionsUpdate/form/${id}`)
  //获取生成规则
  let rules = res.data.rule
  //获取需要设置的规则
  let uploadIndex = rules.findIndex((item, index) => {
    return item.field === "download_url"
  })
  //对该规则设置onSuccess事件
  rules[uploadIndex].props.onSuccess = (info, file) => {
    console.log('info', info, 'file', file)
    file.url = info.data.src
    //旧文档是这么写法的,V2版本无效,需要注意
    // return info.data.src 
  }
  console.log('rules[uploadIndex]', rules[uploadIndex])

  return res
}

方法二:通过组件公共配置上传组件的onSuccess回调函数

其实,为了方便以后不用每个组件去写,我们可以约定每个上传接口的返回格式一致。根据查阅文档,发现插件支持组件公共配置:

文档地址:http://www.form-create.com/v2/guide/common-props.html

  option: {
      // 全局配置
      global: {
          // 上传组件公共配置
          upload: {
              props: {
                   // 上传成功回调
                   onSuccess: (response, file, fileList) => {
                        //返回上传链接(通用,这样设置插插件才能获取到上传回调文件地址)
                        file.url = response.data.src
                        //旧文档是这么写法的,V2版本无效,需要注意
                        // return info.data.src 
                    }
               }
         }
     }
  }

你可能感兴趣的:(2020-09-06 form-create插件 后端表单生成上传组件在前端上传回调链接地址无法自动获取的解决办法)