vue+elementUI上傳圖片至七牛云組件封裝及循環使用

1.效果(解決循環組件賦值問題)在這里插入圖片描述
廢話不多說直接上代碼
2.下載七牛云依賴

npm install qiniu-js
# 或者使用 yarn
yarn add qiniu-js

3.在vue組件中引入

import * as qiniu from 'qiniu-js'

4.在components文件夾下創建UploadImg1/uploadImg.vue組件

<template><div:style="{display: 'grid','justify-content': 'space-between','grid-template-columns': `repeat(auto-fill,minmax(${w},1fr))`}"class="imgBoxSty"><divclass="img-list-item common mb_10":style="{ width: w }"v-for="(item, index) in fileList":key="index"><!-- <videov-if="!matchType(item.name)":style="{ width: w, height: h, margin: '0 9px' }"controls="controls":src="item.url">您的瀏覽器不支持視頻播放</video> --><el-image@mouseover="srcList = [item]":preview-src-list="srcList":style="{ width: w, height: h, margin: '0 9px' }":src="item"fit="cover"></el-image><i class="del-img" @click="forkImage(index)" v-if="isShowImg == true"></i></div><div v-if="maxlength < limit" @click="change"><el-upload:multiple="imgmultiple"action="":data="dataObj":show-file-list="false":auto-upload="true":on-remove="handleRemove":on-success="handleUploadSuccess":before-upload="beforeUpload":on-progress="uploadVideoProcess":http-request="FileForQiNiu"><spanclass="warpss":style="{ width: w, height: h, lineHeight: h }"v-if="isShowImg == true"><iclass="el-icon-plus":style="{color: '#8C939D',fontSize: '18px',fontWeight: 'bold',padding: paddings}"></i></span></el-upload></div></div>
</template>
<script>
import { GetqiniuToken } from "@/api/tools/qiniu";//這個是獲取七牛云token接口,由后端提供
import * as qiniu from "qiniu-js";//引入七牛云依賴
// 或者按需導入(推薦)
export default {name: "uploadImg",props: {//是否多選imgmultiple: {type: Boolean,default: false},//是否需要上傳圖片(false:需要,true:不需要,只能查看圖片不能做任何操作)isShowImg: {type: Boolean,default: false},//個數顯示limit: {type: Number,default: 5},maxlength: {type: Number},value: Array,//最大上傳圖片數量maxCount: {type: Number,default: 5},//寬度w: {type: String// default:'100px'},//高度h: {type: String// default:'100px'},paddings: {type: String},// 上傳類型,1圖片,2視頻,3圖片或視頻uploadType: {type: Number,default: 1}},data: function() {return {flag: true,srcList: [],videoFlag: false,isShow: true,videoUploadPercent: 0,count: 5,videis: false,dataObj: {policy: "",signature: "",key: "",ossaccessKeyId: "",dir: "",host: ""},dialogVisible: false,dialogImageUrl: []};},computed: {fileList() {return this.value;}},mounted() {if (this.fileList.length < this.limit) {this.isShow = true;} else {this.isShow = false;}},methods: {//圖片視頻匹配matchType(name) {// console.log("圖片視頻匹配");//后綴獲取let suffic = "";//獲取類型結果let result = "";try {let fileArr = name.split(".");suffic = fileArr[fileArr.length - 1];// console.log('suffic',suffic);} catch (error) {suffic = "";}//圖片格式var imgList = ["png", "jpg", "jpeg", "bmp", "gif"];//進行圖片匹配result = imgList.some(item => {return item === suffic;});// console.log('結果',result);if (result) {result = "image";// console.log('結果',result);return result;}},//刪除視頻/圖片forkImage(index) {console.log("刪除視頻/圖片", this.fileList, "索引", index);// var data = this.fileList.splice(index, 1);// this.$emit("delFile", this.fileList);// if (this.fileList.length < this.limit) {//   this.isShow = true;// } else {//   this.isShow = false;// }// 創建新數組而不是修改原數組// 創建新數組(不要直接修改props)const newFileList = [...this.value];newFileList.splice(index, 1);// 只使用input事件更新數據this.$emit("input", newFileList);// 更新顯示狀態this.isShow = newFileList.length < this.limit;},change() {// console.log("change函數", this.fileList);if (this.fileList.length < this.limit) {this.isShow = true;} else {this.isShow = false;}},getUUID() {return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, c => {return (c === "x"? (Math.random() * 16) | 0: "r&0x3" | "0x8").toString(16);});},emitInput(fileList) {// console.log("emitInput韓束", fileList);if (!this.flag) {return false;}let value = [];for (let i = 0; i < fileList.length; i++) {value.push(fileList[i]);}this.$emit("input", value);},handleRemove(file, fileList) {if (this.flag) {// console.log("handleRemove函數", file, fileList);this.emitInput(fileList);}},//上傳圖片/視頻成功后的操作handleUploadSuccess(res, file) {console.log("handleUploadSuccess函數上傳圖片/視頻成功");const url =this.dataObj.host +"/" +this.dataObj.key.replace("${filename}", file.name);const newFileList = [...this.value, url];this.$emit("input", newFileList);if (newFileList.length >= this.limit) {this.$message({message: `最多只能上傳${this.limit}個文件`,type: "warning",duration: 1000});}},//進度條uploadVideoProcess(event, file, fileList) {this.videoUploadPercent = Math.floor(event.percent);},beforeUpload(file) {this.flag = true;// 上傳限制視頻//let vedioArr = [// "video/mp4",//  "video/m4v",//  "video/ogg",//  "video/flv",//"video/avi",// "video/wmv",//  "video/rmvb"//  ];// 上傳限制圖片let imgArr = ["image/jpeg", "image/PNG", "image/gif", "image/png"];// 既可上傳圖片、視頻let bothArr = ["video/mp4","video/m4v","video/ogg","video/flv","video/avi","video/wmv","video/rmvb","image/jpeg","image/PNG","image/gif","image/png"];//視頻/圖片校驗if ([// "video/mp4",// "video/m4v",// "video/ogg",// "video/flv",// "video/avi",// "video/wmv",// "video/rmvb","image/jpeg","image/PNG","image/gif","image/png"].indexOf(file.type) == -1) {this.$message.error("請上傳正確的視頻/圖片格式");this.flag = false;// return false;}console.log("canshu", this.flag);return this.flag;},// 獲取七牛云tokenFileForQiNiu(param) {GetqiniuToken().then(response => {console.log("七牛云上傳", response);const key ="七牛云創建的文件夾名稱/" +this.formatTimestamp(new Date().getTime()) +"_" +param.file.size +param.file.name;const observable = qiniu.upload(param.file,key,response,{},{ useCdnDomain: true });observable.subscribe(res => {param.onProgress({ percent: res.total.percent });},err => console.error(err),res => {const newFileList = [...this.value,"https://域名/" + res.key];this.$emit("input", newFileList);});});},formatTimestamp(timestamp) {// 如果 timestamp 是字符串,嘗試轉換為數字const time = new Date(typeof timestamp === "string" ? parseInt(timestamp) : timestamp);// 獲取各個時間部分const year = time.getFullYear();const month = String(time.getMonth() + 1).padStart(2, "0"); // 月份從0開始,所以要+1const day = String(time.getDate()).padStart(2, "0");const hours = String(time.getHours()).padStart(2, "0");const minutes = String(time.getMinutes()).padStart(2, "0");const seconds = String(time.getSeconds()).padStart(2, "0");// 拼接成格式化的字符串return `${year}_${month}_${day}${hours}${minutes}${seconds}`;}}
};
</script>
<style lang="scss" scoped>
.warpss {display: inline-block;border: 1px dashed #dee5ed;margin-left: 13px;
}::v-deep.el-upload-list {display: none;
}.el-upload-video {width: 149px;height: 149px;border: 1px dashed #d9d9d9;border-radius: 6px;cursor: pointer;position: relative;overflow: hidden;
}.el-upload-video-i {font-size: 20px;font-weight: bold;padding-top: 43px;color: #8c939d;width: 50px;height: 50px;line-height: 50px;text-align: center;
}//視頻
.img-list-item {position: relative;margin: auto;
}.img-list-item i.del-img {width: 20px;height: 20px;display: inline-block;background: rgba(0, 0, 0, 0.6);background-image: url(../../assets/images/close.png);//關閉按鈕圖標background-size: 18px;background-repeat: no-repeat;background-position: 50%;position: absolute;top: 0;right: -7px;
}
.imgBoxSty {// display: flex;// flex-wrap: wrap;// justify-content: flex-start;width: 100% !important;// border: 1px solid;// grid-gap: 40px 30px;
}
</style>

5.父組件引用

<template>
<div>
<div  v-for="(item, index) in form.resources" :key="index"><upload-img@input="handleImageChange(index, $event)":isShowImg="isShowImg":maxlength="item.imageArr.length":limit="1"w="100px"h="100px"v-model="item.imageArr"></upload-img>
</div></div>
</<template>import uploadImg from "@/components/UploadImg1/uploadImg.vue";export default {components: { uploadImg },data() {return {form:{isShowImg:true,resources:[{img: "",activityName: "",jumpType: "", //類型jumpLink: "", //商品/科普/運營/自我診療/外部鏈接參數path: "", //路徑imageArr: [] //拿到的圖片}]}}},methods: {handleImageChange(index, newValue) {// this.form.resources[index].imageArr = [newValue];// this.form.resources[index].img = newValue[0];// 使用Vue.set確保響應式更新this.$set(this.form.resources, index, {...this.form.resources[index],imageArr: newValue,img: newValue[0] || "" // 保持同步});this.$forceUpdate();console.log("獲取圖片數據", index, "圖片", newValue, this.form.resources);},}}

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

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

相關文章

2025年6月電子學會青少年軟件編程(C語言)等級考試試卷(一級)

答案和更多內容請查看網站&#xff1a;【試卷中心 -----> 電子學會 ----> C/C ----> 一級】 網站鏈接 青少年軟件編程歷年真題模擬題實時更新 一、編程題 第 1 題 希望如光 題目描述 在充滿挑戰的生活中&#xff0c;希望往往是支撐人們穿越黑暗的核心力量。這…

拒絕復雜,AI圖表制作簡單化

在信息爆炸的時代&#xff0c;數據可視化已成為傳遞信息的核心手段。無論是職場匯報中的業績分析&#xff0c;還是學術研究里的實驗數據呈現&#xff0c;一張清晰直觀的圖表往往能勝過千言萬語。而 AI 技術的介入&#xff0c;徹底改變了圖表制作的傳統模式 —— 它不僅讓零基礎…

easypoi生成多個sheet的動態表頭的實現

在使用 EasyPOI 導出 Excel 時&#xff0c;生成多個 Sheet 且每個 Sheet 的表頭是動態的&#xff08;即每個 Sheet 的列數和列名可能不同&#xff09;&#xff0c;可以通過如下方式實現&#xff1a;? 實現原理簡述 使用 Workbook workbook ExcelExportUtil.exportExcel(expor…

移除鏈表元素+反轉鏈表+鏈表的中間節點+合并兩個有序鏈表+環形鏈表約瑟夫問題+分割鏈表

一、移除鏈表元素 給你一個鏈表的頭節點 phead 和一個整數 val &#xff0c;請你刪除鏈表中所有滿足 Node.val val 的節點&#xff0c;并返回 新的頭節點 (列表中的節點數目在范圍 [0, 104] 內) 示例&#xff1a;輸入&#xff1a;head [1,2,6,3,4,5,6], val 6 …

vue3+arcgisAPI4示例:軌跡點模擬移動(附源碼下載)

demo源碼運行環境以及配置運行環境&#xff1a;依賴Node安裝環境&#xff0c;需要安裝Node。 運行工具&#xff1a;vscode或者其他工具。 配置方式&#xff1a;下載demo源碼&#xff0c;vscode打開&#xff0c;然后順序執行以下命令&#xff1a; &#xff08;1&#xff09;下載…

Design Compiler:Milkyway庫的創建與使用

相關閱讀 Design Compilerhttps://blog.csdn.net/weixin_45791458/category_12738116.html?spm1001.2014.3001.5482 DC Ultra推出了拓撲模式&#xff0c;在綜合時會對標準單元進行粗布局(Coarse Placement)并使用虛擬布線(Virtual Routing)技術計算互聯延遲&#xff0c;關于拓…

嵌入式教學的云端革命:高精度仿真如何重塑倒車雷達實驗與工程教育——深圳航天科技創新研究院賦能新一代虛實融合實訓平臺

一、嵌入式教學的困境與破局之道 在傳統嵌入式系統教學中&#xff0c;硬件依賴始終是核心痛點。以“倒車雷達實驗”為例&#xff0c;學生需操作STM32開發板、超聲波傳感器、蜂鳴器等硬件&#xff0c;面臨設備損耗、接線錯誤、調試效率低等問題。更關鍵的是&#xff0c;物理硬件…

flutter-boilerplate-project 學習筆記

項目地址&#xff1a; https://github.com/zubairehman/flutter_boilerplate_project/tree/master 樣板包含創建新庫或項目所需的最小實現。存儲庫代碼預加載了一些基本組件&#xff0c;例如基本應用程序架構、應用程序主題、常量和創建新項目所需的依賴項。通過使用樣板代碼…

集成電路學習:什么是CMSIS微控制器軟件接口標準

CMSIS,即Cortex Microcontroller Software Interface Standard(Cortex微控制器軟件接口標準),是由ARM公司與多家不同的芯片和軟件供應商緊密合作定義的一個標準。該標準旨在為基于ARM Cortex處理器的微控制器提供一套與供應商無關的硬件抽象層,從而簡化軟件的開發、重用,…

由淺入深使用LangGraph創建一個Agent工作流

創建一個簡單的工作流&#xff1a;Start ——> 節點1(固定輸入輸出) ——> Endfrom langchain_core.messages import SystemMessage, HumanMessage, AIMessage from langgraph.graph import StateGraph, START, END from typing_extensions import TypedDict from typing…

PL-0功能拓展及基于VSCode的IDE配置

title: PL/0功能拓展及基于VSCode的IDE配置 date: 2024-08-06 22:46:38 tags: 做過的實驗||項目復盤 top: true 概述PL/0語言可以看成PASCAL語言的子集,它的編譯程序是由C語言編寫的編譯解釋執行系統。PL/0能充分展示高級語言的最基本成分。拓展了pl0語言的基礎功能&#xff08…

【低空經濟】大型露天礦區安全生產無人機巡查與管理系統設計

1. 引言 大型露天礦區因其廣闊的作業區域和復雜的環境條件&#xff0c;安全生產管理面臨著嚴峻的挑戰。隨著科技的進步&#xff0c;無人機作為一種現代化的巡查工具&#xff0c;逐漸被應用于礦區的安全生產管理中。無人機具備高效、靈活、成本相對低廉等優點&#xff0c;可以在…

SpringCloud學習第一季-3

目錄 11.服務網關-Gateway新一代網關 一、Gateway概述 1、Gateway是什么 1.1 概述 2、 能干嘛 3、微服務架構中網關在哪里 4、為什么選擇gateway? 4.1 SpringCloud Gateway具有如下特性 4.2 SpringCloud Gateway 與 Zuul的區別 5、Zuul1.x模型 6、gateway模型 二、…

超越邊界:MongoDB 16MB 文檔限制的 pragmatic 解決方案

在軟件開發中&#xff0c;我們選擇的技術棧往往帶有一些固有的設計邊界。對于 MongoDB 而言&#xff0c;其最著名的邊界之一便是 BSON 文檔最大 16MB 的大小限制。在大多數場景下&#xff0c;這個限制是綽綽有余的&#xff0c;它鼓勵開發者設計更為精簡和規范的數據模型。然而&…

深入探討:PostgreSQL正則表達式中的郵政編碼匹配

引言 在處理大量數據時,如何高效地從字符串中提取特定模式的文本,如郵政編碼,是一個常見且具有挑戰性的任務。本文將通過一個具體實例,探討在PostgreSQL中使用正則表達式匹配加拿大郵政編碼的問題,并提供解決方案。 問題描述 我們希望能夠從字符串中提取所有符合加拿大…

集合框架(重點)

第十五天集合框架1.什么是集合 Collections集合Collection&#xff0c;也是一個數據容器&#xff0c;類似于數組&#xff0c;但是和數組是不一樣的。集合是一個可變的容器&#xff0c;可以隨時向集合中添加元素&#xff0c;也可以隨時從集合中刪除元素。另外&#xff0c;集合還…

深度學習核心:神經網絡-激活函數 - 原理、實現及在醫學影像領域的應用

&#x1f9d1; 博主簡介&#xff1a;CSDN博客專家、CSDN平臺優質創作者&#xff0c;高級開發工程師&#xff0c;數學專業&#xff0c;10年以上C/C, C#,Java等多種編程語言開發經驗&#xff0c;擁有高級工程師證書&#xff1b;擅長C/C、C#等開發語言&#xff0c;熟悉Java常用開發…

OneCode3.0 核心表達式技術深度剖析:從架構設計到動態擴展

一、引言&#xff1a;表達式技術在企業級框架中的核心價值 在當今快速變化的企業級應用開發中&#xff0c;動態性和靈活性已成為衡量框架優劣的關鍵指標。OneCode 3.0 框架作為企業級應用開發的重要工具&#xff0c;其核心表達式技術提供了一種強大的解決方案&#xff0c;使開發…

[css]旋轉流光效果

實現一個矩形的旋轉流光邊框效果。 需要使用css屬性梯度漸變&#xff1a;鏈接: conic-gradient&#xff0c;他指的是圓錐形變化的梯度。 // html<div class"demo"></div>// css body {width: 100%;height: 100%;background-color: black; }.demo {width…

NPM組件 @0xme5war/apicli 等竊取主機敏感信息

【高危】NPM組件 0xme5war/apicli 等竊取主機敏感信息 漏洞描述 當用戶安裝受影響版本的 0xme5war/apicli 等NPM組件包時會竊取用戶的主機名、用戶名、工作目錄、IP地址等信息并發送到攻擊者的電報地址(botToken “7699295118:AAF6pb7t718vjHWHwFQlZOastZQYHL8IVDE”&#x…