问题描述
最近开始踩坑 element-ui 发现upload组件 一直用不好 下面这是组件信息
当我新增数据时 使用upload组件 会调用:on-change="handleShowImage" 不知道为什么提交成功后 在给form.adUrl 赋值(服务器返回的链接地址)后 又自动的调用了一次:on-change="handleShowImage" 事件 它改变了我上传成功的地址链接 转成了本地地址的链接
景及自己尝试过哪些方法
相关代码
// 请把代码文本粘贴到下方(请勿用图片代替代码)
<el-form-item label="banner图片" :label-width="formLabelWidth" prop="adUrl">
<el-upload
class="avatar-uploader"
action=""
ref="upload"
:auto-upload='false'
:show-file-list="false"
:on-error="handleVideoError"
:on-exceed="beyondFile"
:on-change="handleShowImage"
:on-success="handleVideoSuccess"
:http-request="fnUploadRequest"
:before-upload="beforeAvatarUpload"
:limit='10'
multiple>
<img v-if="form.adUrl" :src="form.adUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
submitUpload() {// 点击确认提交按钮提交
this.$refs.upload.submit();
},
// 自定义上传覆盖默认上传
async fnUploadRequest(option) {
console.log(222222222222222222);
oss.ossUploadFile(option);
},
// 文件超出个数限制时的钩子
beyondFile(files, fileList) {
this.$message({message: '只能上传limit',type: 'error'});
},
// 上传失败
handleVideoError(){
this.$message({message: '上传失败',type: 'error'});
},
// 上传成功
handleVideoSuccess(response, file, fileList) {
console.log(33333333333333);
if(response){
this.form.adUrl= ossURL+response.name;
if(this.message.modelTitle === '新建广告' || this.message.isEdit){// 判断是新增还是修改 是新增
this.$post(adSave,this.form)
.then(res => {
console.log(res);
if(res.status === 200){
if(this.message.isEdit){
this.$message({message: '修改成功',type: 'success'});
}else{
this.$message({message: '新增成功',type: 'success'});
}
this.changeGetPageData(this.paging.page, this.paging.rows, this.searchForm.status);
this.resetForm('ruleForm');
this.message.isEdit = false;
}
})
.catch(error => {
console.log(error);
})
}
}
},
handleShowImage(file){
console.log(999999999999);
// 添加判定 提交数据的会自动调用这个函数 this.form.adUrl 添加验证 不会被本地地址覆盖 暂时性解决
if(this.message.modelTitle === '新建广告' && this.form.adUrl === ''){
this.form.adUrl = URL.createObjectURL(file.raw);// 图片数据回显
}
if(this.message.modelTitle === '新建广告' && this.form.adUrl.substring(0,14) !== 'http://oss-xzb'){
this.form.adUrl = URL.createObjectURL(file.raw);// 图片数据回显
}
if(this.message.modelTitle === '修改广告'){
this.form.adUrl = URL.createObjectURL(file.raw);
this.message.isEdit = true;
}
},
// 文件验证
beforeAvatarUpload(file) {
console.log(11111111111111111);
const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png' || file.type ==='image/gif');
const isLt2M = file.size / 1024 / 1024 < 20;
if (!isJPG) {
this.$message.error('上传图片只能是 JPG,PNG,GIF 格式!');
}
if (!isLt2M) {
this.$message.error('上传图片大小不能超过 20MB!');
}
return isJPG && isLt2M;
},
你期待的结果是什么?实际看到的错误信息又是什么?
是我哪里写错了么?一直没有找到原因
修改-----------------------------------------
是的 不管成功还是失败 或是修改图片 都会调用on-chang事件
有什么办法可以解决 上传成功后 调用了on-change事件 不会改变this.form.adUrl我要提交到服务器的真正的值
我也遇到这个问题了,后面在onchange事件中做以下判断
如果是成功或者失败的回调,status不是ready。可以通过这个来筛选,只有文件改变的时候才可以继续。