vue2組件封裝+elementUI

1.VUE2圖片上傳封裝

使用

   <ImageUpload v-model="picUrl" :fileSize="0"  @getImg="getImg"></ImageUpload>

封裝代碼

<template><div class="component-upload-image"><el-uploadmultiple:action="uploadImgUrl"list-type="picture-card":on-success="handleUploadSuccess":before-upload="handleBeforeUpload":limit="limit":on-error="handleUploadError":on-exceed="handleExceed"ref="imageUpload":on-remove="handleDelete":show-file-list="true":headers="headers":file-list="fileList":on-preview="handlePictureCardPreview":class="{hide: this.fileList.length >= this.limit}"><i class="el-icon-plus"></i></el-upload><!-- 上傳提示 --><div class="el-upload__tip" slot="tip" v-if="showTip">請上傳<template v-if="fileSize"> 大小不超過 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template><template v-if="fileType"> 格式為 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>的文件</div><el-dialog:visible.sync="dialogVisible"title="預覽"width="800"append-to-body><img:src="dialogImageUrl"style="display: block; max-width: 100%; margin: 0 auto"/></el-dialog></div>
</template><script>
import { getToken } from "@/utils/auth";
import { listByIds, delOss } from "@/api/system/oss";export default {props: {value: [String, Object, Array],// 圖片數量限制limit: {type: Number,default: 5,},// 大小限制(MB)fileSize: {type: Number,default: 5,},// 文件類型, 例如['png', 'jpg', 'jpeg']fileType: {type: Array,default: () => ["png", "jpg", "jpeg"],},// 是否顯示提示isShowTip: {type: Boolean,default: true}},data() {return {number: 0,uploadList: [],dialogImageUrl: "",dialogVisible: false,hideUpload: false,baseUrl: process.env.VUE_APP_BASE_API,uploadImgUrl: process.env.VUE_APP_BASE_API + "/system/oss/upload", // 上傳的圖片服務器地址headers: {Authorization: "Bearer " + getToken(),},fileList: []};},watch: {value: {async handler(val) {if (val) {// 首先將值轉為數組let list;if (Array.isArray(val)) {list = val;} else {await listByIds(val).then(res => {list = res.data;this.$emit("getImg", list);})}// 然后將數組轉為對象數組this.fileList = list.map(item => {// 此處name使用ossId 防止刪除出現重名item = { name: item.ossId, url: item.url, ossId: item.ossId };return item;});} else {this.fileList = [];return [];}},deep: true,immediate: true}},computed: {// 是否顯示提示showTip() {return this.isShowTip && (this.fileType || this.fileSize);},},methods: {// 上傳前loading加載handleBeforeUpload(file) {let isImg = false;if (this.fileType.length) {let fileExtension = "";if (file.name.lastIndexOf(".") > -1) {fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);}isImg = this.fileType.some((type) => {if (file.type.indexOf(type) > -1) return true;if (fileExtension && fileExtension.indexOf(type) > -1) return true;return false;});} else {isImg = file.type.indexOf("image") > -1;}if (!isImg) {this.$modal.msgError(`文件格式不正確, 請上傳${this.fileType.join("/")}圖片格式文件!`);return false;}if (this.fileSize) {const isLt = file.size / 1024 / 1024 < this.fileSize;if (!isLt) {this.$modal.msgError(`上傳頭像圖片大小不能超過 ${this.fileSize} MB!`);return false;}}this.$modal.loading("正在上傳圖片,請稍候...");this.number++;},// 文件個數超出handleExceed() {this.$modal.msgError(`上傳文件數量不能超過 ${this.limit} 個!`);},// 上傳成功回調handleUploadSuccess(res, file) {if (res.code === 200) {this.uploadList.push({ name: res.data.fileName, url: res.data.url, ossId: res.data.ossId });this.uploadedSuccessfully();} else {this.number--;this.$modal.closeLoading();this.$modal.msgError(res.msg);this.$refs.imageUpload.handleRemove(file);this.uploadedSuccessfully();}},// 刪除圖片handleDelete(file) {const findex = this.fileList.map(f => f.name).indexOf(file.name);if(findex > -1) {let ossId = this.fileList[findex].ossId;// delOss(ossId);this.fileList.splice(findex, 1);this.$emit("input", this.listToString(this.fileList));}},// 上傳失敗handleUploadError(res) {this.$modal.msgError("上傳圖片失敗,請重試");this.$modal.closeLoading();},// 上傳結束處理uploadedSuccessfully() {if (this.number > 0 && this.uploadList.length === this.number) {this.fileList = this.fileList.concat(this.uploadList);this.uploadList = [];this.number = 0;this.$emit("input", this.listToString(this.fileList));this.$modal.closeLoading();}},// 預覽handlePictureCardPreview(file) {this.dialogImageUrl = file.url;this.dialogVisible = true;},// 對象轉成指定字符串分隔listToString(list, separator) {let strs = "";separator = separator || ",";for (let i in list) {if (list[i].ossId) {strs += list[i].ossId + separator;}}return strs != "" ? strs.substr(0, strs.length - 1) : "";}}
};
</script>
<style scoped lang="scss">
// .el-upload--picture-card 控制加號部分
::v-deep.hide .el-upload--picture-card {display: none;
}
// 去掉動畫效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {transition: all 0s;
}::v-deep .el-list-enter, .el-list-leave-active {opacity: 0;transform: translateY(0);
}
</style>

2.文件上傳封裝

使用

 <FileUpload v-model="fileIds" :fileSize="0"  @getfile="getfile"></FileUpload>

封裝代碼

<template><div class="upload-file"><el-uploadv-if="isUpload"multiple:action="uploadFileUrl":before-upload="handleBeforeUpload":file-list="fileList":limit="limit":on-error="handleUploadError":on-exceed="handleExceed":on-success="handleUploadSuccess":show-file-list="false":headers="headers"class="upload-file-uploader"ref="fileUpload"><!-- 上傳按鈕 --><el-button size="mini" type="primary">選取文件</el-button><!-- 上傳提示 --><div class="el-upload__tip" slot="tip" v-if="showTip">請上傳<template v-if="fileSize">大小不超過 <b style="color: #f56c6c">{{ fileSize }}MB</b></template><template v-if="fileType">格式為 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>的文件</div></el-upload><!-- 文件列表 --><transition-groupclass="upload-file-list el-upload-list el-upload-list--text"name="el-fade-in-linear"tag="ul"v-if="isFileList"><li:key="file.url"class="el-upload-list__item ele-upload-list__item-content"style="padding: 0 4px"v-for="(file, index) in fileList"><el-link :href="`${file.url}`" :underline="false" target="_blank"><span class="el-icon-document"> {{ getFileName(file.name) }} </span></el-link><div class="ele-upload-list__item-content-action" v-if="isUpload"><el-link :underline="false" @click="handleDelete(index)" type="danger">刪除</el-link></div></li></transition-group></div>
</template><script>
import { getToken } from "@/utils/auth";
import { listByIds, delOss } from "@/api/system/oss";export default {name: "FileUpload",props: {// 值value: [String, Object, Array],// 數量限制limit: {type: Number,default: 5,},// 大小限制(MB)fileSize: {type: Number,default: 5,},// 文件類型, 例如['png', 'jpg', 'jpeg']fileType: {type: Array | Boolean,// default: () => ["doc", "xls", "ppt", "txt", "pdf"],default: () => ["doc", "docx", "xls", "xlsx", "ppt", ".pptx", "pdf"],},// 是否顯示提示isShowTip: {type: Boolean,default: true,},// 是否顯示文件列表isFileList: {type: Boolean,default: true,},dataIndex: {type: Number | String,default: 0,},// 是否可以上傳isUpload: {type: Boolean,default: true,},},data() {return {number: 0,uploadList: [],baseUrl: process.env.VUE_APP_BASE_API,uploadFileUrl: process.env.VUE_APP_BASE_API + "/system/oss/upload", // 上傳文件服務器地址headers: {Authorization: "Bearer " + getToken(),},fileList: [],};},watch: {value: {async handler(val) {if (val) {let temp = 1;// 首先將值轉為數組let list;if (Array.isArray(val)) {list = val;} else {console.log(val);await listByIds(val).then((res) => {list = res.data.map((oss) => {oss = {name: oss.originalName,url: oss.url,ossId: oss.ossId,};return oss;});this.$emit("getfile", list, this.dataIndex);});}// 然后將數組轉為對象數組this.fileList = list.map((item) => {item = { name: item.name, url: item.url, ossId: item.ossId };item.uid = item.uid || new Date().getTime() + temp++;return item;});} else {this.fileList = [];return [];}},deep: true,immediate: true,},},computed: {// 是否顯示提示showTip() {return this.isShowTip && (this.fileType || this.fileSize);},},methods: {// 上傳前校檢格式和大小handleBeforeUpload(file) {// 校檢文件類型if (this.fileType) {const fileName = file.name.split(".");const fileExt = fileName[fileName.length - 1];const isTypeOk = this.fileType.indexOf(fileExt) >= 0;if (!isTypeOk) {this.$modal.msgError(`文件格式不正確, 請上傳${this.fileType.join("/")}格式文件!`);return false;}}// 校檢文件大小if (this.fileSize) {const isLt = file.size / 1024 / 1024 < this.fileSize;if (!isLt) {this.$modal.msgError(`上傳文件大小不能超過 ${this.fileSize} MB!`);return false;}}this.$modal.loading("正在上傳文件,請稍候...");this.number++;return true;},// 文件個數超出handleExceed() {this.$modal.msgError(`上傳文件數量不能超過 ${this.limit} 個!`);},// 上傳失敗handleUploadError(err) {this.$modal.msgError("上傳文件失敗,請重試");this.$modal.closeLoading();},// 上傳成功回調handleUploadSuccess(res, file) {if (res.code === 200) {this.uploadList.push({name: res.data.fileName,url: res.data.url,ossId: res.data.ossId,});this.uploadedSuccessfully();} else {this.number--;this.$modal.closeLoading();this.$modal.msgError(res.msg);this.$refs.fileUpload.handleRemove(file);this.uploadedSuccessfully();}},// 刪除文件handleDelete(index) {let ossId = this.fileList[index].ossId;// delOss(ossId);this.fileList.splice(index, 1);this.$emit("input", this.listToString(this.fileList));},// 上傳結束處理uploadedSuccessfully() {if (this.number > 0 && this.uploadList.length === this.number) {this.fileList = this.fileList.concat(this.uploadList);this.uploadList = [];this.number = 0;this.$emit("input", this.listToString(this.fileList));this.$modal.closeLoading();}},// 獲取文件名稱getFileName(name) {// 如果是url那么取最后的名字 如果不是直接返回if (name.lastIndexOf("/") > -1) {return name.slice(name.lastIndexOf("/") + 1);} else {return name;}},// 對象轉成指定字符串分隔listToString(list, separator) {let strs = "";separator = separator || ",";for (let i in list) {strs += list[i].ossId + separator;}return strs != "" ? strs.substr(0, strs.length - 1) : "";},},
};
</script><style scoped lang="scss">
.upload-file-uploader {margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {border: 1px solid #e4e7ed;line-height: 2;margin-bottom: 10px;position: relative;
}
.upload-file-list .ele-upload-list__item-content {display: flex;justify-content: space-between;align-items: center;color: inherit;
}
.ele-upload-list__item-content-action .el-link {margin-right: 10px;
}
</style>

3.圖片回顯

使用

 <ImagePreview :src="content.picUrl" :width="150" :height="150"></ImagePreview>

封裝代碼

<template><div><el-image v-for="(item,index) in realSrcList" :key="index":src="`${item}`"fit="cover":style="`width:${realWidth};height:${realHeight};`":preview-src-list="realSrcList"><div slot="error" class="image-slot"><i class="el-icon-picture-outline"></i></div></el-image></div></template><script>export default {name: "ImagePreview",props: {src: {type: String,default: ""},width: {type: [Number, String],default: ""},height: {type: [Number, String],default: ""}},computed: {realSrc() {if (!this.src) {return;}let real_src = this.src.split(",")[0];return real_src;},realSrcList() {if (!this.src) {return;}let real_src_list = this.src.split(",");let srcList = [];real_src_list.forEach(item => {return srcList.push(item);});return srcList;},realWidth() {return typeof this.width == "string" ? this.width : `${this.width}px`;},realHeight() {return typeof this.height == "string" ? this.height : `${this.height}px`;}},
};
</script><style lang="scss" scoped>
.el-image {border-radius: 5px;background-color: #ebeef5;box-shadow: 0 0 5px 1px #ccc;::v-deep .el-image__inner {transition: all 0.3s;cursor: pointer;&:hover {transform: scale(1.2);}}::v-deep .image-slot {display: flex;justify-content: center;align-items: center;width: 100%;height: 100%;color: #909399;font-size: 30px;}
}
</style>

4.文件回顯

使用

   <FileUpload v-model="content.fileIds" :isShowTip="false" :fileType="false" :isUpload="false"></FileUpload>

5.樹形封裝

使用

 <orginTree v-model="form.deptId" @getdep="getdep"></orginTree>

組件封裝代碼

<template><div><a-tree-selectv-model="orgId"style="width: 100%"size="large":dropdown-style="{ maxHeight: '400px', overflow: 'auto', zIndex: 3000 }"placeholder="請選擇"allow-cleartree-default-expand-all:disabled="disabled":tree-data="vorganTreeData":replaceFields="replaceFields"@change="onChange"></a-tree-select></div>
</template><script>
//注意!!!!!
//在modal彈窗組件中使用該組件需要在關閉彈窗方法里清空數據否則會報錯
import { userdepList } from "@/api/user/user";
export default {name: "vorganTree",props: {value: {// 如果希望value可以接收int類型的值而不報錯,可以將type類型修改為可以兼容字符串和整數的類型type: [String, Number],default: "",},disabled: {type: Boolean,default: false,},replaceFields: {type: Object,default: () => {return {children: "children",title: "label",key: "id",value: "id",};},},},data() {return {orgId: this.value,vorganTreeData: [],deptId: "",};},watch: {value: {handler(newVal) {this.orgId = newVal;},immediate: true,},},mounted() {// this.$bus.$on("id", (data) => {//   console.log("我是任務組件,收到了數據", data);//   this.deptId = data;// });this.deptId = this.$bus.id;this.userdepList();},methods: {userdepList() {userdepList({ ancestors: this.deptId }).then((res) => {console.log("res.data", res);this.vorganTreeData = res.data;});},selectClear() {this.orgId = undefined;},onChange(value, item, xx) {console.log(11111, value, item, xx);// this.$emit("update:value", value);this.$emit("getdep", value);},},
};
</script><style scoped lang="less">
</style>

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/21986.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/21986.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/21986.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

react 合成事件

React合成事件-CSDN博客 當然&#xff0c;很高興為你解釋React中的合成事件概念&#xff0c;非常適合React初學者理解。 想象一下&#xff0c;你正在組織一場派對&#xff0c;為了讓派對順利進行&#xff0c;你需要管理各種活動&#xff0c;比如游戲、音樂和食物分配。但是&a…

C語言之指針進階(5),sizeof和strlen的數組計算以及指針運算筆試難題詳解

目錄 前言 一、sizeof和strlen 的區分比較 二、sizeof,strlen與數組的計算 三、指針運算&#xff0c;筆試難題解析 總結 前言 本文作為指針進階的最后一篇文章&#xff0c;給大家帶來了豐富的例題&#xff0c;這其中包括區分比較sizeof和strlen計算各種花樣的數組指針表達式…

Redis的SDS數據結構解決C語言字符串缺陷

redis設計了SDS這一數據結構來表示字符串而不是使用c語言的字符串&#xff1a;字符數組 那么redis為什么要大費周章自己設計字符串呢&#xff1f; 答案是C語言字符串有缺陷 1.獲取字符串長度&#xff0c;需要遍歷字符數組&#xff0c;時間復雜度是O&#xff08;N&#xff09…

Springboot vue3 elementplus 景點評論數據分析與可視化系統源碼

源碼鏈接 系統演示:鏈接&#xff1a;https://pan.baidu.com/s/1J056R4rYji_mc4gwteZEzg?pwdnua4

關于Linux系統用戶和用戶組的使用

天行健&#xff0c;君子以自強不息&#xff1b;地勢坤&#xff0c;君子以厚德載物。 每個人都有惰性&#xff0c;但不斷學習是好好生活的根本&#xff0c;共勉&#xff01; 文章均為學習整理筆記&#xff0c;分享記錄為主&#xff0c;如有錯誤請指正&#xff0c;共同學習進步。…

教程 | 在 Navicat 17 中管理連接

Navicat 17 提供了比以往更多的連接數據庫實例的方式。除了傳統的連接字符串方式以外&#xff0c;Navicat 17 還支持 URI 連接&#xff0c;無論身在何處&#xff0c;都可以輕松地通過 URI 訪問對象。另外&#xff0c;還有一個新的管理連接功能&#xff0c;即允許你通過一個以用…

【LeetCode】39.組合總和

組合總和 題目描述&#xff1a; 給你一個 無重復元素 的整數數組 candidates 和一個目標整數 target &#xff0c;找出 candidates 中可以使數字和為目標數 target 的 所有 不同組合 &#xff0c;并以列表形式返回。你可以按 任意順序 返回這些組合。 candidates 中的 同一個…

高中數學:平面向量-常考題型匯總

一、數量積運算 例題1 解析 首先&#xff0c;為了化簡運算過程&#xff0c;我們把OA、OB、OC向量記作a、b、c向量。 其次&#xff0c;充分利用已知條件&#xff0c;進行消元&#xff0c;兩邊平方&#xff0c;可以消除一個向量。 a → \mathop{a}\limits ^{\rightarrow} a→ *…

【簡單探索微軟Edge】

&#x1f3a5;博主&#xff1a;程序員不想YY啊 &#x1f4ab;CSDN優質創作者&#xff0c;CSDN實力新星&#xff0c;CSDN博客專家 &#x1f917;點贊&#x1f388;收藏?再看&#x1f4ab;養成習慣 ?希望本文對您有所裨益&#xff0c;如有不足之處&#xff0c;歡迎在評論區提出…

(delphi11最新學習資料) Object Pascal 學習筆記---第14章泛型第2節(Object Pascal中的泛型)

14.2 Object Pascal中的泛型 ? 在前面的例子中&#xff0c;我們已經看到了如何在Object Pascal中定義和使用泛型類。我決定在深入討論這個非常重要但又相當復雜的技術細節之前&#xff0c;通過一個例子來介紹泛型這一特性。在從語言角度討論泛型之后&#xff0c;我們將列舉更…

Hadoop文件存儲格式

1. TextFile 默認格式&#xff0c;存儲方式為行存儲&#xff0c;數據不做壓縮&#xff0c;磁盤開銷大&#xff0c;數據解析開銷大。可結合 Gzip、Bzip2 使用(系統自動檢查&#xff0c;執行查詢時自動解壓)&#xff0c;但使用 這種方式&#xff0c;壓縮后的文件不支持 split&am…

2024.6.3總結1100

今天面試了一家廣西電信公司&#xff0c;然后受到武漢華為的hr的電話溝通&#xff0c;如果沒意外的話&#xff0c;下周就能收到offer了。 求職也算是踏入社會的第一步了&#xff0c;經過兩個月的求職過程&#xff0c;我除了關于求職方面的技巧&#xff0c;也擴展了我的認知。 …

R語言安裝caret包報錯

R語言安裝caret包報錯&#xff1a;Error: package or namespace load failed for ‘caret’ in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck vI[[i]]): 不存在叫‘recipes’這個名字的程輯包 https://rbasics.org/packages/caret-package-in-r/ R版本的問題&…

商業新聞|你還在用傳統搜索引擎嗎?

??今天是2024年第22周 這是Yura「輸出倒逼輸入」計劃的第11篇文章 全年進度&#xff1a;11/52 01 AI搜索為什么沒超過傳統搜索&#xff1f; 生成式AI在搜索引擎領域掀起了一輪又一輪的波瀾&#xff0c;但是一年多過去了&#xff0c;不管是必應還是perplexity都并沒有動搖Goog…

深度解讀GPT基本原理

GPT&#xff08;Generative Pre-trained Transformer&#xff09;是一種基于Transformer架構的生成式預訓練模型&#xff0c;其核心在于通過大規模無監督學習來捕捉語言知識和模式&#xff0c;并通過微調來適應各種下游任務。以下是GPT基本原理的詳細解讀&#xff1a; 1.Trans…

pandas習題 036:選擇 DataFrame 的多個列

有以下一個 DataFrame&#xff0c;請從中選擇 name 和 english 這兩列形成一個 DataFrame。 import pandas as pddata {name: [Alice, Bob, Charlie, David, Eve],grade: [10, 11, 10, 12, 11],math: [90, 85, 92, 88, 95],english: [85, 92, 88, 90, 92],science: [92, 90, …

【TB作品】MSP430G2553霓虹燈呼吸燈跑馬燈

霓虹燈&#xff1a; 跑馬燈&#xff1a; 呼吸燈&#xff1a; 所有代碼&#xff1a; 下載&#xff1a; https://docs.qq.com/sheet/DUEdqZ2lmbmR6UVdU?tabBB08J2

蘋果CMS:怎么添加2019和2020年份篩選

我們進入搜索的時候看到一個關于年份的搜索&#xff0c;那如果上面沒有出現19,20我們該如何處理呢&#xff1f; 我們進入管理后臺 -【系統】-【網站參數配置】-【預留參數】 添加下視頻年代逗號隔開即可 如果要設置地區&#xff0c;語言也實在這里直接配置即可&#xff01;&am…

毫米波雷達陣列天線設計綜合1(MATLAB仿真)

1 天線設計目標 毫米波雷達探測目標的距離、速度和角度&#xff0c;其中距離和角度和天線設計相關性較強。天線增益越高&#xff0c;則根據雷達方程可知探測距離越遠&#xff1b;天線波束越窄&#xff0c;則角度分辨率越高&#xff1b;天線副瓣/旁瓣越低&#xff0c;則干擾越少…

Kibana的使用

在學習elasticsearch時&#xff0c;可以使用Kibana自帶的開發工具&#xff0c;來提高效率&#xff0c; 瀏覽器打開Kibana,在左側菜單欄中找到Dev Tools 該工具提供代碼提示和代碼格式化功能&#xff0c;非常有用&#xff0c;