Vue開發——封裝上傳檔案元件
阿新 • • 發佈:2019-02-13
使用elementui的 el-upload外掛實現圖片上傳元件每個專案存在一定的特殊性,所以資料的處理會不同 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" alt=""> </el-dialog> </div></template><script>import { getToken } from "@/utils/auth";import store from "@/store";export default { props: { imgList: { type: Array, default: [] }, // 父元件傳遞的圖片列表 limit: "" // 圖片數量限制 }, data() { return { fileList: [], upLoadData: { img: "" }, baseUrl: process.env.BASE_API, dialogVisible: false, dialogImageUrl: "", headers: { Authorization: store.getters.token_type + " " + store.getters.token } // 介面呼叫token }; }, watch: { // 監聽imgList的變化: fileList要求的格式為[{url: img}],所以監聽imgList變化後將其進行處理,賦值給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: { // 圖片移除時處理資料 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; }, // 判斷圖片數量 handleExceed(files, fileList) { this.$message.warning(`當前限制選擇 ${this.limit} 個檔案,本次選擇了 ${files.length} 個檔案,共選擇了 ${files.length + fileList.length} 個檔案`); }, 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);},