el-upload实现可替换、删除、预览的图片上传。js 往返缓存(可判断当前页面是不是返回的页面)

本文主要是介绍el-upload实现可替换、删除、预览的图片上传。js 往返缓存(可判断当前页面是不是返回的页面),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

el-upload实现可替换、删除、预览的图片上传

在这里插入图片描述

  • 组件使用:
<template><div><UploadImage sendUrl='' :limit="1" :size="size" :gifSize="gifSize" v-model="images"></UploadImage> </div>
</template>
<script>import Vue from 'vue'import UploadImage from './UploadImage.vue'export default {components: {UploadImage},data(){retun {images:'',size: 400 * 1024,ifSize: 1 * 1024 * 1024,// images:[]}}}
</script>
  • UploadImage.vue 组件:
<template><div class="uploadFileMain" :style="{'--height':`${height}px`,'--width':`${width}px`}"><div v-for="(item,index) in fileList" :key="index" class="upload-list" :class="[limit==1?'upload-lis1':'']"><div v-if="switchIndex==index && showProgress" v-loading="true" class="loadingView" element-loading-background="rgba(0, 0, 0, 0.8)" /><img :id="`${idName}_image_${index}`" class="el-upload-listImg" :src="item.url"  alt=""><span class="el-actions"><spanclass="el-upload-icon"@click="handlePictureCardPreview(index,item.url)"><i class="el-icon-zoom-in" /></span><spanclass="el-upload-icon"@click="switchFn(index)"><i class="el-icon-sort" style="transform: rotate(90deg);" /></span><spanclass="el-upload-icon"@click="delRemove(index)"><i class="el-icon-delete" /></span></span></div><el-uploadv-show="!limit || fileList.length<limit":ref="`${idName}_upload`":show-file-list="false":multiple="multiple":limit="limit?limit+1:limit":action="sendUrl"list-type="picture-card":headers="{Authorization: $utils.getToken()}":accept="acceptArray.length>0?acceptArray.map(n=>this.acceptType[n]).join(',') :'*'":file-list="fileList":before-upload="beforeUpload":on-progress="progressFn":on-success="uploadSuccess"><div v-if="switchIndex==-1 && showProgress" v-loading="true" :style="{'height':`${height}px`,'width':`${width}px`}" class="loadingView" element-loading-background="rgba(0, 0, 0, 0.8)" /><div v-else  class="uploadClick" :id="`${idName}_uploadClick`" slot="trigger" @click="changeIndex(-1)"><i class="el-icon-plus"  /></div></el-upload></div>
</template>
<script>
import Vue from 'vue'export default {props: {sendUrl: {type: String,default: ''},value: {type: [Array, String],default: ''},width: {type: [Number, String],default: 80},height: {type: [Number, String],default: 80},multiple: {type: Boolean,default: true},limit: {type: Number,default: null// default: 4},// 大小限制:10 * 1024 * 1024 = 10MBsize: {type: Number,default: -1},//   限制类型,按照acceptType数组里面来acceptArray: {type: Array,default: () => {return ['png', 'jpg', 'jpeg', 'gif']}},gifSize: {type: Number,default: -1}},data() {return {acceptType: {'doc': 'application/msword','docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document','pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation','xls': 'application/vnd.ms-excel','xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','pdf': 'application/pdf','csv': '.csv','txt': 'text/plain','image': 'image/*','png': 'image/png','gif': 'image/gif','jpg': 'image/jpg','jpeg': 'image/jpeg'},idName: `${Math.random().toString(36).slice(-8)}_${new Date().getTime()}`,switchIndex: -1,fileList: [],dataArray: {1: [],2: []},showProgress: false}},watch: {value: {handler(value) {if (Array.isArray(value)) {this.fileList = value.filter(n => n != '').map(n => {return {url: n}})} else {this.fileList = value.split(',').filter(n => n != '').map(n => {return {url: n}})}},deep: true,immediate: true},fileList: {handler(value) {if (value.length > 0) {this.toFileImg(value)}},deep: true,immediate: true},dataArray: {handler(value) {// 1 和 2 相等表示这次上传成功的数量相同,会添加到数组里面if (value[1].length != 0 && value[2].length != 0 && value[1].length == value[2].length) {value[2].forEach(e => {// 有更换就变化if (this.switchIndex != -1) {this.fileList.splice(this.switchIndex, 1, {status: 'success',url: e.data})} else {// 没有更好追加this.fileList.push({status: 'success',url: e.data})}})setTimeout(() => {this.showProgress = falsethis.switchIndex = -1}, 300)this.dataArray = {1: [],2: []}}},deep: true}},methods: {async lookImageViewer(url, list) {let listImg = listconst thisIndex = list.indexOf(url)const firstArray = list.slice(thisIndex, list.length)const twoArray = list.slice(0, thisIndex)listImg = [...firstArray, ...twoArray]// this.$viewerApi({ images: listImg })//v-viewer组件const id = 'MyElImageViewer_' + new Date().getTime() + '_' + parseInt(Math.random() * 1000)// 引用组件(找到Elementui中image-viewer的位置)const ElImageViewer = (await import('element-ui/packages/image/src/image-viewer')).defaultconst MyElImageViewer = Vue.component('MyElImageViewer', ElImageViewer)const MyElImageViewerNew = new MyElImageViewer({propsData: {urlList: listImg,onClose: () => {// 删除组件compDOm.$destroy()document.body.removeChild(document.getElementById(id))}}})const DOM = document.createElement('div')DOM.setAttribute('id', id)DOM.setAttribute('class', 'imageSwipeViewer_Show')document.body.appendChild(DOM)// 挂载组件const compDOm = MyElImageViewerNew.$mount(DOM.appendChild(document.createElement('template')))compDOm.$nextTick(() => {const showDom = document.getElementById(id)showDom.querySelector('.el-icon-circle-close').style = 'font-size:38px;color:#fff'})},filterSize(size) {const pow1024 = (num) => {return Math.pow(1024, num)}if (!size) return ''if (size < pow1024(1)) return size + ' B'if (size < pow1024(2)) return (size / pow1024(1)).toFixed(0) + ' KB'if (size < pow1024(3)) return (size / pow1024(2)).toFixed(0) + ' MB'if (size < pow1024(4)) return (size / pow1024(3)).toFixed(0) + ' GB'return (size / pow1024(4)).toFixed(2) + ' TB'},// 上传之前放到1beforeUpload(e) {const fileSize = e.sizeif (this.gifSize > 0) {if (e.type.indexOf('gif') != -1 && fileSize > this.gifSize) {this.$message.error(`gif最大上传${this.filterSize(this.gifSize)}`)return false}} else {if (this.size > 0 && fileSize > this.size) {this.$message.error(`最大上传${this.filterSize(this.size)}`)return false}}this.dataArray[1].push({status: 'uploading',...e})return true},// 通过 slot="trigger" ,区分模拟点击,表示这次时人为点击的changeIndex(index) {if (index == -1) {this.switchIndex = -1}},progressFn(e) {this.showProgress = true},// 更换图片,模拟点击switchFn(index) {document.getElementById(`${this.idName}_uploadClick`).click(this.switchIndex)setTimeout(() => {this.switchIndex = index}, 0)},// 查看图片handlePictureCardPreview(index, url) {this.lookImageViewer(url, [url])},// 成功后放到2uploadSuccess(e) {this.dataArray[2].push({...e})},// 传递图片toFileImg(value) {if (Array.isArray(this.value)) {this.$emit('input', value.map(n => n.url))} else {this.$emit('input', value.map(n => n.url).join(','))}},delRemove(index) {this.fileList.splice(index, 1)if (this.fileList.length == 0) {this.toFileImg(this.fileList)}}}}
</script>
<style lang="scss" scoped>::v-deep .el-upload--picture-card{width: var(--width);display:flex;justify-content:center;align-items:center;height: var(--height);}.uploadClick{width: var(--width);display:flex;justify-content:center;align-items:center;height: var(--height);}::v-deep .el-upload-list--picture-card .el-upload-list__item{width: var(--width);display:flex;align-items:center;height: var(--height);transition: none !important;}::v-deep .el-upload-list__item .el-icon-check{position: absolute;margin-top: 0px;top: 10px;right: 14px;}::v-deep .el-loading-spinner{width: 100%;height: 100%;top: 0;margin-top: 0;display: flex;align-items: center;justify-content: center;}::v-deep .el-upload-list,::v-deep .el-upload-list--picture-card{//display: none;}.uploadFileMain{display: flex;flex-wrap: wrap;.upload-list{flex-shrink:0;width: var(--width);border:1px solid #0000005d;box-sizing: border-box;height: var(--height);margin-right: 20px;margin-bottom: 10px;&.upload-lis1{margin-bottom: 0px;}overflow: hidden;border-radius: 8px;position: relative;.el-actions{position: absolute;width: 100%;height: 100%;top: 0;left: 0;background-color: rgba(0,0,0,0.5);align-items: center;justify-content: center;display: none;.el-upload-icon{margin: 5px;i{color: #ffffff;cursor: pointer;}}}&:hover{.el-actions{display: flex;}}}.el-upload-listImg{width: 100%;height: 100%;object-fit: contain;}}.loadingView{width: 100%;height: 100%;}
</style>

往返缓存(BFCache)

BFCache是一种浏览器优化,可实现即时前进和后退载入页面。它改善了用户的浏览体验,尤其是那些网络或设备速度较慢的用户。*我们可以通过这个方法判断当前页面是不是返回的页面*

在APP站内嵌套h5页面,判断进入拨号页返回情况:

  • 我们需要通过visibilitychange

  • 通过在点击时修改一个状态值,回来时和上面的方法进行判断

    const isClick=false // 是否点击了离开页面按钮
    const isShowPop=false // 是否显示弹窗
    document.addEventListener('visibilitychange', () => {if (document.visibilityState == "visible") {if (isClick) {isShowPop = true}isClick = false} else {}
    })
    

如果是在浏览器里面,判断进入拨号页(三方客服链接)返回情况:

  • 在浏览器里面如果是离开了页面还是可以通过visibilitychange判断,但是跳转的是三方客服链接,那我我们回到页面,页面是会重新刷新的,我们需要知道是否返回了,就需要通过performance.getEntriesByType('navigation')[0].type

  • 同时通过在点击时修改一个状态值,回来时和上面的方法进行判断

    const isClick=false // 是否点击了离开页面按钮
    const isShowPop=false // 是否显示弹窗
    const pageshowFn=(event)=> {const navigationType = performance.getEntriesByType('navigation')[0].typeconst {persisted = null} = eventif (persisted || navigationType == 'back_forward') {isShowPop = trueisClick = false
    }
    }
    window.removeEventListener('pageshow', pageshowFn)
    window.addEventListener('pageshow', pageshowFn)
    // 页面初次进入需要调用
    pageshowFn({})

往返缓存(BFCache)具体详解

这篇关于el-upload实现可替换、删除、预览的图片上传。js 往返缓存(可判断当前页面是不是返回的页面)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/592057

相关文章

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

Python正则表达式匹配和替换的操作指南

《Python正则表达式匹配和替换的操作指南》正则表达式是处理文本的强大工具,Python通过re模块提供了完整的正则表达式功能,本文将通过代码示例详细介绍Python中的正则匹配和替换操作,需要的朋... 目录基础语法导入re模块基本元字符常用匹配方法1. re.match() - 从字符串开头匹配2.

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

Python一次性将指定版本所有包上传PyPI镜像解决方案

《Python一次性将指定版本所有包上传PyPI镜像解决方案》本文主要介绍了一个安全、完整、可离线部署的解决方案,用于一次性准备指定Python版本的所有包,然后导出到内网环境,感兴趣的小伙伴可以跟随... 目录为什么需要这个方案完整解决方案1. 项目目录结构2. 创建智能下载脚本3. 创建包清单生成脚本4

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

Nginx部署HTTP/3的实现步骤

《Nginx部署HTTP/3的实现步骤》本文介绍了在Nginx中部署HTTP/3的详细步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录前提条件第一步:安装必要的依赖库第二步:获取并构建 BoringSSL第三步:获取 Nginx

MyBatis Plus实现时间字段自动填充的完整方案

《MyBatisPlus实现时间字段自动填充的完整方案》在日常开发中,我们经常需要记录数据的创建时间和更新时间,传统的做法是在每次插入或更新操作时手动设置这些时间字段,这种方式不仅繁琐,还容易遗漏,... 目录前言解决目标技术栈实现步骤1. 实体类注解配置2. 创建元数据处理器3. 服务层代码优化填充机制详

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函

Java实现字节字符转bcd编码

《Java实现字节字符转bcd编码》BCD是一种将十进制数字编码为二进制的表示方式,常用于数字显示和存储,本文将介绍如何在Java中实现字节字符转BCD码的过程,需要的小伙伴可以了解下... 目录前言BCD码是什么Java实现字节转bcd编码方法补充总结前言BCD码(Binary-Coded Decima