vue项目中封装手动上传多个图片并支持修改和移除

现有的组件库无法满足手动上传文件到服务器,并支持通过按钮修改和移除文件的操作。所以我利用原生input进行封装,如有需要请拿走

vue项目中封装手动上传多个图片并支持修改和移除_第1张图片

1.页面部分

    
选择图片

2、逻辑部分

export default {
    props: {
        imageList: {
            type: Array,
            default: () => []
        },
    },
    data() {
        return {
            pictureIndex: "",
            clearInputShow: true,
        }
    },
    methods: {
        // 上传
        selectPicture() {
            this.$refs.uploadfile.click();
        },
        // 修改
        updatePicture(index) {
            this.pictureIndex = index
            this.$refs.uploadfile.click();
        },
        // 移除文件
        remove(index) {
            this.$emit("update:imageList", this.imageList.filter((item, i) => i != index))
        },
        // 手动上传文件
        onChangeFile() {
            // file上传的文件
            let file = this.$refs.uploadfile.files[0];
            const formData = new FormData()
            // 上传文件的参数都以这种方法
            formData.append('file', file)
            formaData.append('fileName', file.name)
            this.clearInputShow = false;
            // 上传接口
            this.$axios.post('接口地址', formData).then(res => {
                this.clearInputShow = true;
                // 假设res.data.picUrl是接口返回图片路径
                // 没有下标,说明是新增,有下标是修改
                if (this.pictureIndex === "") {
                    this.$emit("update:imageList", [...this.imageList, res.data.picUrl])
                    this.pictureIndex = ""
                } else {
                    this.imageList.splice(this.pictureIndex, 1, res.data.picUrl)
                    this.$emit("update:imageList", [...this.imageList])
                    this.pictureIndex = ""
                }
            }).catch((error)=>{
                this.clearInputShow = true;
            })
        },
    }
}

3、样式部分

你可能感兴趣的:(vue.js,javascript,前端)