您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)使用Vue怎么封裝一個(gè)文件上傳組件,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
pictureupload.vue:
<template> <div class="pictureupload"> <el-upload :action="baseUrl + '/api/public/image'" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :file-list="fileList" :on-exceed="handleExceed" :before-remove="beforeRemove" name="img" :on-success="upLoadSuccess" :data="upLoadData" :headers="headers" :limit="limit"> <i class="el-icon-plus"></i> </el-upload> <el-dialog :visible.sync="dialogVisible"> <img width="100%" :src="dialogImageUrl" > </el-dialog> </div> </template> <script> import { getToken } from "@/utils/auth"; import store from "@/store"; export default { props: { imgList: { type: Array, default: [] }, // 父組件傳遞的圖片列表 limit: "" // 圖片數(shù)量限制 }, data() { return { fileList: [], upLoadData: { img: "" }, baseUrl: process.env.BASE_API, dialogVisible: false, dialogImageUrl: "", headers: { Authorization: store.getters.token_type + " " + store.getters.token } // 接口調(diào)用token }; }, watch: { // 監(jiān)聽(tīng)imgList的變化: fileList要求的格式為[{url: img}],所以監(jiān)聽(tīng)imgList變化后將其進(jìn)行處理,賦值給fileList imgList: { handler(newValue, oldValue) { if(newValue.length === 0) { this.fileList = []; return; } for (let i = 0; i < newValue.length; i++) { if (oldValue[i] != newValue[i]) { this.fileList = []; newValue.forEach(el => { this.fileList.push({url: el}) }) return; } } }, deep: true } }, methods: { // 圖片移除時(shí)處理數(shù)據(jù) handleRemove(file, fileList) { let item = []; fileList.forEach(el => { item.push(el.url); }); this.$emit("removeimg", item); }, handlePictureCardPreview(file) { this.dialogImageUrl = file.url; this.dialogVisible = true; }, // 判斷圖片數(shù)量 handleExceed(files, fileList) { this.$message.warning(`當(dāng)前限制選擇 ${this.limit} 個(gè)文件,本次選擇了 ${files.length} 個(gè)文件,共選擇了 ${files.length + fileList.length} 個(gè)文件`); }, beforeRemove(file, fileList) {}, // 上傳圖片成功事件 upLoadSuccess(response) { this.$emit("uploadimg", response.message); this.$message("上傳成功",); } }, mounted() { if (this.imgList.length != 0) { this.imgList.forEach(el => { this.fileList.push({ url: el }); }); } } }; </script>
使用上傳圖片組件:
<pictureupload @uploadimg="uploadimg" :imgList="ruleForm.img" :limit="3" @removeimg="removeimg"></pictureupload>
removeimg(item) { this.ruleForm.img = item; }, uploadimg(item) { this.ruleForm.img.push(item); },
關(guān)于使用Vue怎么封裝一個(gè)文件上傳組件就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。