對(duì)element-ui上傳組件Upload 再簡(jiǎn)化

重置組件目的

對(duì)Upload 上傳組件在簡(jiǎn)化的目的是對(duì)文件上傳前的限制都統(tǒng)一到組件中去完成不在繁瑣的每個(gè)去寫嗜诀,同時(shí)增加上傳后圖片的大圖預(yù)覽隆敢,音頻試聽筑公,視頻觀看等尊浪。

組件代碼(簡(jiǎn)化后代碼基本兼容原有使用方法除了slot="file"外)

<template>
    <div>
        <el-upload :class="(listType=='single' && !$slots.default)? 'avatar-uploader':''" :action="url"
                   :headers="headers" :data="data" :multiple="multiple" :name="name" :drag="drag"
                   :with-credentials="withCredentials" :disabled="disabled" :limit="limit"
                   :show-file-list="isShowFileList" :list-type="customListType" :fileList="fileList"
                   :auto-upload="autoUpload" :http-request="httpRequest"
                   :before-upload="handleBeforeUpload"
                   :on-success="handleSuccess"
                   :on-exceed="handleExceed"
                   :on-error="handleError"
                   :on-preview="handlePreview"
                   :on-change="handleChange"
                   :on-progress="handleProgress"
                   :before-remove="handleBeforeRemove"
                   :on-remove="handleRemove">
            <template v-if="drag && !$slots.default">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                    {{$t('pages.common.dragFilesHere')}}<em>{{$t('pages.common.clickUpload')}}</em></div>
            </template>
            <!--單圖片上傳-->
            <template v-else-if="listType=='single' && !$slots.default">
                <el-image v-if="imageUrl" :src="imageUrl" class="avatar"></el-image>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </template>
            <template v-else-if="(listType=='picture-card' || listType=='video') && !$slots.default">
                <i class="el-icon-plus"></i>
            </template>
            <template v-else-if="!$slots.default">
                <el-button size="small" type="primary">{{$t('pages.common.clickUpload')}}</el-button>
            </template>
            <slot></slot>
            <template slot="file" slot-scope="{file}" v-if="listType=='video'">
                <el-progress v-if="file.status === 'uploading'" type="circle"
                             :stroke-width="6"
                             :percentage="parsePercentage(file.percentage)">
                </el-progress>
                <div class="el-upload-list__item-thumbnail" v-if="file">
                    <video class="el-upload-list__item-thumbnail" :src="file.url"></video>
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-preview"
                            @click="handlePreview(file)">
                        <i class="sx-icon-video" style="font-size: 19px"></i>
                      </span>
                      <span class="el-upload-list__item-delete">
                        <i class="el-icon-delete" @click="handleRemove(file,fileList)"></i>
                      </span>
                    </span>
                </div>
            </template>
        </el-upload>
        <!-- 查看大圖   -->
        <el-dialog title="大圖預(yù)覽" :visible.sync="dialogImageVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="大圖">
        </el-dialog>
        <!--觀看視頻-->
        <el-dialog title="賞析視頻" :visible.sync="dialogVideoVisible" @close="handlePause" append-to-body>
            <video ref="video" style="width: 100%; height: 100%; display: block; outline: none;" :src="dialogVideoUrl"
                   controls
                   autoplay></video>
        </el-dialog>
        <!--試聽音頻-->
        <el-dialog title="試聽音頻" :visible.sync="dialogAudioVisible" @close="handlePause" append-to-body>
            <audio ref="audio" style="width: 100%; height: 50px; display: block; outline: none;" :src="dialogAudioUrl"
                   controls
                   autoplay></audio>
        </el-dialog>
    </div>
</template>

<script>
    import isEqual from 'lodash/isEqual'

    /*自定義上傳 - element-ui上傳再封裝*/
    export default {
        name: "ElUploadCustom",
        data() {
            return {
                dialogImageVisible: false,
                dialogImageUrl: null,
                dialogVideoVisible: false,
                dialogVideoUrl: null,
                dialogAudioVisible: false,
                dialogAudioUrl: null,
                imageUrl: ''
            }
        },
        model: {
            prop: 'value',
            event: 'change'
        },
        props: {
           value:{
                type: Array,
                default() {
                    return [];
                }
            },
            action: {
                type: String,
                required: true
            },
            headers: {
                type: Object,
                default() {
                    return {};
                }
            },
            data: Object,
            multiple: Boolean,
            name: {
                type: String,
                default: 'file'
            },
            drag: Boolean,
            accept: String,
            flieSize: Number,
            withCredentials: Boolean,
            showFileList: {
                type: Boolean,
                default: true
            },
            listType: {
                type: String,
                default: 'text' // text,picture,picture-card single:單圖片上傳 video:上傳視頻 audio: 上傳音頻
            },
            disabled: Boolean,
            limit: Number,
            fileList: {
                type: Array,
                default() {
                    return [];
                }
            },
            autoUpload: {
                type: Boolean,
                default: true
            },
            httpRequest: Function,
            beforeUpload: Function,
            beforeRemove: Function,
            onRemove: Function,
            onChange: Function,
            onPreview: Function,
            onSuccess: Function,
            onProgress: Function,
            onError: Function,
            onExceed: Function
        },
        watch: {
            fileList: {
                handler: function (val) {
                    if (this.listType == 'single') {
                        this.imageUrl = val.length ? val[0].url : '';
                    }
                },
                immediate: true
            }
        },
        computed: {
            url() {
                if (/^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+/.test(this.action)) {
                    return this.action
                } else {
                    if (typeof this.httpRequest == "function") {
                        return '#';
                    } else {
                        return this.$http.defaults.baseURL + this.action;
                    }
                }
            },
            isShowFileList() {
                if (this.listType == 'single') {
                    return false;
                } else {
                    return this.showFileList;
                }
            },
            customListType() {
                if (this.listType == 'single' || this.listType == 'audio') {
                    return 'text';
                } else if (this.listType == 'video') {
                    return 'picture-card';
                } else {
                    return this.listType
                }
            }
        },
        methods: {
            //文件上傳前事件
            handleBeforeUpload(file) {
                if (this.beforeUpload) {
                    return this.beforeUpload(file);
                } else {
                    //判斷文件類型
                    const typeLimit = this.accept ? this.accept.split(',').includes(file.type) : true;
                    //判斷文件大小
                    const sizeLinit = this.flieSize ? file.size / 1024 < this.flieSize : true;
                    if (!typeLimit) {
                        this.$message.error(this.$t('pages.common.uploadFileType', {type: this.accept}));
                    }
                    if (!sizeLinit) {
                        let flieSize = this.flieSize > 1024 ? parseInt(this.flieSize / 1024) + 'M' + this.flieSize % 1024 : this.flieSize;
                        this.$message.error(this.$t('pages.common.uploadFileSize', {size: flieSize}));
                    }
                    return typeLimit && sizeLinit;
                }
            },
            //文件上傳超出限制事件
            handleExceed(files, fileList) {
                if (this.onExceed) {
                    this.onExceed(files, fileList);
                } else {
                    this.$message.error(this.$t('pages.common.uploadFileNumber', {number: this.limit}))
                }
            },
            //上傳進(jìn)度事件
            handleProgress(event, file, fileList) {
                if (this.onProgress) {
                    this.onProgress(event, file, fileList)
                }
            },
            //上傳成功事件
            handleSuccess(res, file, fileList) {
                if (this.onSuccess) {
                    this.onSuccess(res, file, fileList);
                } else {
                    if (!res.code) {
                        if (this.listType == 'single') {
                            file.url = res.data;
                            this.imageUrl = res.data;
                            this.$emit('change', [file]);
                        } else {
                            fileList.forEach(item => {
                                if (isEqual(item, file)) {
                                    item.url = res.data
                                }
                            });
                            this.$emit('change', fileList);
                        }
                    } else {
                        this.handleRemove(file, fileList);
                        this.$message.error(this.$t('pages.common.uploadFileError'));
                    }
                }
            },
            //預(yù)覽事件
            handlePreview(file) {
                if (this.onPreview) {
                    this.onPreview(file);
                } else {
                    if (this.listType == 'audio') {
                        this.dialogAudioUrl = file.url;
                        this.dialogAudioVisible = true;
                        if (this.$refs.video) {
                            this.$refs.video.remove()
                        }
                    } else if (this.listType == 'video') {
                        this.dialogVideoUrl = file.url;
                        this.dialogVideoVisible = true;
                        if (this.$refs.audio) {
                            this.$refs.audio.remove()
                        }
                    } else {
                        //沒有提供文件類型就下載判定
                        if (!file.raw) {
                            let xhr = new XMLHttpRequest();
                            xhr.open("GET", file.url, true);
                            xhr.responseType = "blob";
                            xhr.onload = () => {
                                file.raw = xhr.response
                                //判斷當(dāng)前點(diǎn)擊文件是否為圖片類型 是顯示大圖預(yù)覽
                                if (['image/png', 'image/jpeg', 'image/gif', 'application/x-jpg', 'application/x-png'].includes(file.raw.type)) {
                                    this.dialogImageUrl = file.url;
                                    this.dialogImageVisible = true;
                                }
                                //判斷當(dāng)前點(diǎn)擊文件是否為音頻類型 是顯示試聽音頻
                                if (['audio/mp3'].includes(file.raw.type)) {
                                    this.dialogAudioUrl = file.url;
                                    this.dialogAudioVisible = true;
                                }
                                //判斷當(dāng)前點(diǎn)擊文件是否為視頻類型 是顯示賞析視頻
                                if (['video/mp4'].includes(file.raw.type)) {
                                    this.dialogVideoUrl = file.url;
                                    this.dialogVideoVisible = true;
                                }
                            };
                            xhr.send();
                        } else {
                            //判斷當(dāng)前點(diǎn)擊文件是否為圖片類型 是顯示大圖預(yù)覽
                            if (['image/png', 'image/jpeg', 'image/gif'].includes(file.raw.type)) {
                                this.dialogImageUrl = file.url;
                                this.dialogImageVisible = true;
                            }
                            //判斷當(dāng)前點(diǎn)擊文件是否為音頻類型 是顯示試聽音頻
                            if (['audio/mp3'].includes(file.raw.type)) {
                                this.dialogAudioUrl = file.url;
                                this.dialogAudioVisible = true;
                            }
                            //判斷當(dāng)前點(diǎn)擊文件是否為視頻類型 是顯示賞析視頻
                            if (['video/mp4'].includes(file.raw.type)) {
                                this.dialogVideoUrl = file.url;
                                this.dialogVideoVisible = true;
                            }
                        }
                    }
                }
            },
            //上傳失敗事件
            handleError(err, file, fileList) {
                if (this.onError) {
                    this.onError(err, file, fileList);
                } else {
                    this.handleRemove(file, fileList);
                    this.$message.error(this.$t('pages.common.uploadFileError'));
                }
            },
            //文件移除前事件
            handleBeforeRemove(file, fileList) {
                if (this.beforeRemove) {
                    this.beforeRemove(file, fileList);
                }

            },
            //刪除事件
            handleRemove(file, fileList) {
                if (this.onRemove) {
                    this.onRemove(file, fileList);
                } else {
                    let index = fileList.findIndex(item => item.uid == file.uid);
                    if (index != -1) {
                        fileList.splice(index, 1);
                    }
                    this.$emit('change', fileList);
                }
            },
            //文件狀態(tài)改變事件
            handleChange(file, fileList) {
                if (this.onChange) {
                    this.onChange(file, fileList);
                }
            },
            //暫停播放音頻視頻
            handlePause() {
                if (this.$refs.audio) {
                    this.$refs.audio.pause();
                    this.dialogAudioVisible = false;
                }
                if (this.$refs.video) {
                    this.$refs.video.pause();
                    this.dialogVideoVisible = false;
                }
            },
            //進(jìn)度百分比
            parsePercentage(val) {
                return parseInt(val, 10);
            },
        },
        created() {
        }
    }
</script>

<style scoped>
    .avatar-uploader >>> .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>

組件使用

<template>
  //@getData獲取上傳的文件列表  :flie-size 限制文件上傳大新印(如下限制500kb)不填無(wú)限制 accept限制文件上傳類型(如下只能上傳png和jpg圖片)不填無(wú)限制
  <el-upload-custom v-model="picurls"  list-type="picture-card" :file-list="picurls"
                                      action="/SXBS-INFORMATION/file/uploadFileUsingOriginalFilename"
                                      :flie-size="500" accept="image/png,image/jpeg">
                    </el-upload-custom>
</template>
<script>
  export default {
    methods: {
    
   
    },
    data() {
      return {
          picurls:[]  
      };
    },
    mounted(){
     
    },
    created() {
       
    }
  }
</script>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市键俱,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌缀辩,老刑警劉巖踪央,帶你破解...
    沈念sama閱讀 218,755評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件杯瞻,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡睬涧,警方通過查閱死者的電腦和手機(jī)旗唁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門检疫,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人屎媳,你說我怎么就攤上這事烛谊。” “怎么了丹禀?”我有些...
    開封第一講書人閱讀 165,138評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)持搜。 經(jīng)常有香客問我,道長(zhǎng)辛友,這世上最難降的妖魔是什么剪返? 我笑而不...
    開封第一講書人閱讀 58,791評(píng)論 1 295
  • 正文 為了忘掉前任脱盲,我火速辦了婚禮钱反,結(jié)果婚禮上匣距,老公的妹妹穿的比我還像新娘。我一直安慰自己尚卫,他們只是感情好尸红,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,794評(píng)論 6 392
  • 文/花漫 我一把揭開白布外里。 她就那樣靜靜地躺著,像睡著了一般盅蝗。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上芙委,一...
    開封第一講書人閱讀 51,631評(píng)論 1 305
  • 那天题山,我揣著相機(jī)與錄音故痊,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛焰络,可吹牛的內(nèi)容都是我干的符喝。 我是一名探鬼主播,決...
    沈念sama閱讀 40,362評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼畏腕,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼描馅!你這毒婦竟也來(lái)了而线?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,264評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤嘹狞,失蹤者是張志新(化名)和其女友劉穎誓竿,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體知市,經(jīng)...
    沈念sama閱讀 45,724評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡嫂丙,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,900評(píng)論 3 336
  • 正文 我和宋清朗相戀三年跟啤,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了唉锌。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,040評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡腥放,死狀恐怖绿语,靈堂內(nèi)的尸體忽然破棺而出候址,到底是詐尸還是另有隱情岗仑,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評(píng)論 5 346
  • 正文 年R本政府宣布荠雕,位于F島的核電站炸卑,受9級(jí)特大地震影響煤傍,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜患久,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,364評(píng)論 3 330
  • 文/蒙蒙 一蒋失、第九天 我趴在偏房一處隱蔽的房頂上張望篙挽。 院中可真熱鬧,春花似錦铣卡、人聲如沸偏竟。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)殖蚕。三九已至,卻和暖如春害驹,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背宛官。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留进宝,地道東北人枷恕。 一個(gè)月前我還...
    沈念sama閱讀 48,247評(píng)論 3 371
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像未玻,于是被迫代替她去往敵國(guó)和親胡控。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,979評(píng)論 2 355