In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article will explain in detail how to use Vue3 and element-plus to achieve picture upload components. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
Preface
Element-plus provides a uploader component, but it is difficult to customize, so it builds a wheel and implements a component for uploading images. Its expected behavior is:
1. When the picture is not uploaded, the upload card is displayed.
two。 Show the progress bar when uploading pictures and hide the uploaded cards
3. A thumbnail of the picture is displayed when the upload is successful, and a failure prompt is displayed if the upload fails.
4. Support the preview and deletion of uploaded images
It is shown in the following figure:
Specific code picture upload
The picture bed used here is Niutu, there is no need to register, and there seems to be no limit on the size of the image, but please do not upload illegal images.
Import axios from "axios" import {ElMessage} from 'element-plus'const service = axios.create ({baseURL: "/ image"}) service.interceptors.response.use (response = > {const code = response.data.code | | 200if (code = 200) {return response.data.data} let msg = response.data.code + "" + response.data.msg ElMessage.error (msg) return Promise.reject (' failed to upload image Failure:'+ msg)}) / * upload image * @ param {File} file picture file * @ param {RefImpl} progress upload progress * @ returns promise * / function uploadImage (file Progress) {let formData = new FormData () FormData.append ("file", file) return service ({url: "/ upload", method: "post", data: formData, onUploadProgress (event) {let v = Math.round (event.loaded / event.total * 100) progress.value = v = 100? 80: v},} export {uploadImage}
Here, onUploadProgress is used to monitor the upload progress, but in fact, using the calculated progress directly will often deviate greatly from the actual situation, that is to say, even if you are still uploading, axios will tell you that you have finished uploading, so here you change the progress of 100th to 80, and the real 100th progress should be set when the server returns url.
Limited by the same origin policy, we need to configure the proxy server in vue.config.js:
Module.exports = {devServer: {proxy: {"/ image": {target: "https://niupic.com/api", pathRewrite: {" ^ / image ":"},},}} upload components
The image preview function uses vue-easy-light-box. If you don't have it installed, you can install it with npm install-save vue-easy-lightbox@next. Here is the specific code:
Import {ref, computed} from "vue"; import {uploadImage} from ".. / api/image"; import {Plus} from "@ element-plus/icons-vue"; import VueEasyLightbox from "vue-easy-lightbox"; import {ElMessage} from 'element-plus/lib/components' Export default {name: "KilaKilaUploader", emits: ["uploaded", "aboutToUpload", "removed"], components: {Plus, VueEasyLightbox}, setup (props, context) {let progress = ref (0); let isLightBoxVisible = ref (false); let isProgressVisible = ref (false); let isSuccessLabelVisible = ref (false); let imageUrl = ref ("); let localImageUrl = ref (") Let index = ref (0); let isThumbnailVisible = computed (() = > localImageUrl.value.length > 0); function openFileDialog () {document.getElementById ("file-input"). Click ();} function onImageAdded () {let fileInput = document.getElementById ("file-input"); if (fileInput.files.length = = 0) {return } context.emit ("aboutToUpload"); let file = fileInput.files [0]; setImageUrl (URL.createObjectURL (file)); upload (file);} function setImageUrl (url) {let thumbnailEl = document.getElementById ("thumbnail"); thumbnailEl.src = localImageUrl.value = url } function handleThumbnailRemove (file) {imageUrl.value = "; localImageUrl.value ="; context.emit ("removed", file);} function handleThumbnailPreview () {isLightBoxVisible.value = true;} function handleLightboxHide () {isLightBoxVisible.value = false } function upload (file) {progress.value = 0; isProgressVisible.value = true; isSuccessLabelVisible.value = false; uploadImage (file, progress). Then ((url) = > {progress.value = 100; imageUrl.value = url Document.getElementById ("thumbnail"). Src = url; context.emit ("uploaded", url); setTimeout (() = > {isProgressVisible.value = false; isSuccessLabelVisible.value = true;}, 200) }, () = > {isProgressVisible.value = false; localImageUrl.value = ""; context.emit ("uploaded", ""); ElMessage.error ("Oh, picture upload error ~")}) } return {progress, imageUrl, localImageUrl, index, isLightBoxVisible, isThumbnailVisible, isProgressVisible, isSuccessLabelVisible, handleThumbnailRemove, handleThumbnailPreview, handleLightboxHide, openFileDialog, onImageAdded, setImageUrl,} },}; .uploader {display: flex;}. Card {background-color: # fbfdff; border: 1px dashed # c0cccda; border-radius: 6px; width: 148px; height: 148px; overflow: hidden;}. Upload-card {display: flex; justify-content: center; align-items: center; transition: all 0.3s; cursor: pointer; &: hover {border-color: # 409eff Color: # 409ef;}}. Thumbnail-card {border: 1px solid # c0ccda; position: relative; # thumbnail {width: 100%; height: 100%; object-fit: contain; display: inline;}. Success-label {position: absolute; right:-15px; top:-6px; width: 40px; height: 24px Background: # 67c23a; text-align: center; transform: rotate (45deg); box-shadow: 00 1pc 1px # 0003; .success-icon {position: absolute; left: 13px; top: 1px; transform: rotate (- 45deg);} # progress {width: 100%; height: 100% Position: absolute; top: 0; left: 0; background: rgba (255,255,255,0.7);: deep (.el-progress-circle) {position: absolute; top: 50%; left: 50%; transform: translate (- 50%,-50%) }}. Thumbnail-actions {width: 100%; height: 100%; background: rgba (0,0,0,0.5); opacity: 0; transition: all 0.4s ease; display: flex; justify-content: center; align-items: center; position: absolute; top: 0; left: 0 Border-radius: 6px; .thumbnail-preview, .thumbnail-delete {cursor: pointer; margin: 08px; display: inline-block;} &: hover {opacity: 1;}}: deep (.vel-img) {box-shadow: 0 5px 20px 2px rgba (0,0,0,0.35);}
Custom events are triggered before the image is uploaded, when the upload is completed, and when the image is removed, and the parent component can handle these events to set the image url.
On "how to use Vue3 and element-plus to achieve picture upload components" this article is shared here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, please share it out for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.