element-ui 的upload组件,before-upload验证不通过后触发了on-remove方法的解决办法

1、图示

element-ui 的upload组件,before-upload验证不通过后触发了on-remove方法的解决办法_第1张图片

rt,类似于这样的上传

2、HTML

套图

3、JS

//上传前执行代码
beforeAvatarUpload(file) {
            var isJPG = false;
            switch (file.type) {
                case "image/png":
                    isJPG = true;
                    break;
                case "image/jpeg":
                    isJPG = true;
                    break;
                default:
                    isJPG = false;
                    break;
            }
            const isLt2M = file.size / 1024 / 1024 < 3;
            if (!isJPG) {
                this.$message.error("上传图片只能是 JPG/PNG 格式!");
            }
            if (!isLt2M) {
                this.$message.error("上传图片大小不能超过 3MB!");
            }
            return isJPG && isLt2M;
        },


//删除上传
handleRemove(file) {
            const isType = file.type === 'image/png' || file.name.split('.')[1] === 'image/jpeg';
            if (isType) {
                let url;
            let id;
            if (file.response) {
                url =
                    this.api.book.delete.url +
                    file.response.data.id +
                    "/" +
                    "0";
                id = file.response.data.id;
            } else {
                url =
                    this.api.book.delete.url + file.id + "/" + this.ruleForm.id;
                id = file.id;
            }
            this.axios.post(url).then(res => {
                this.$message({
                    message: "删除成功",
                    type: "success"
                });
                //把相应的id也删除
                let otherImgs = this.ruleForm.otherImgs;
                let arr = [];
                for (let i = 0; i < otherImgs.length; i++) {
                    if (otherImgs[i] != id) {
                        arr.push(otherImgs[i]);
                    }
                }
                this.ruleForm.otherImgs = arr;
            });
            }
            
        },

现在的问题在于,当上传的时候判断上传文件的类型不通过的时候,会触发handleRemove方法,解决办法就是,在删除的时候判断下,该文件类型是不是规定的上传的文件,如果是的话才可以删除,这样的话,如果上传的文件不是规定的文件类型,那么上传不成功,但是因为上传的文件不是规定的文件类型,那么也就不会执行handleRemove方法。如图中const isType = file.type === 'image/png' || file.name.split('.')[1] === 'image/jpeg'; if、、、这段代码。

你可能感兴趣的:(vue)