<!-- * @Description: * @Autor: renchao * @LastEditTime: 2023-09-14 16:21:51 --> <template> <el-image-viewer :on-close="closeViewer" :url-list="urlList" :initial-index="initialIndex"> </el-image-viewer> </template> <script> import ElImageViewer from 'element-ui/packages/image/src/image-viewer' export default { components: { ElImageViewer, }, props: { urlList: { type: Array, default: function () { return [] } }, initialIndex: { type: Number, default: 0 } }, data () { return { wrapperElem: null } }, mounted () { this.$nextTick(() => { let wrapper = document.getElementsByClassName( 'el-image-viewer__actions__inner' ) let downImg = document.createElement('i') downImg.setAttribute('class', 'el-icon-download') wrapper[0].appendChild(downImg) if (wrapper.length > 0) { this.wrapperElem = wrapper[0] this.wrapperElem.addEventListener('click', this.hideCusBtn) } }) }, methods: { /** * @description: closeViewer * @author: renchao */ closeViewer () { this.$emit('close-viewer') }, /** * @description: hideCusBtn * @param {*} e * @author: renchao */ hideCusBtn (e) { let className = e.target.className if (className === 'el-icon-download') { let imgUrl = document.getElementsByClassName( 'el-image-viewer__canvas' )[0].children[0].src this.downloadImage(imgUrl) } }, /** * @description: downloadImage * @param {*} imgUrl * @author: renchao */ downloadImage (imgUrl) { let tmpArr = imgUrl.split('/') let fileName = tmpArr[tmpArr.length - 1] window.URL = window.URL || window.webkitURL let xhr = new XMLHttpRequest() xhr.open('get', imgUrl, true) xhr.responseType = 'blob' xhr.onload = function () { if (this.status == 200) { //得到一个blob对象 let blob = this.response let fileUrl = window.URL.createObjectURL(blob) let a = document.createElement('a') ; (document.body || document.documentElement).appendChild(a) a.href = fileUrl if ('download' in a) { a.download = fileName } else { a.setAttribute('download', fileName) } a.target = '_self' a.click() a.remove() } } xhr.send() }, }, } </script> <style lang="scss" scoped> /deep/ .el-image-viewer__close { color: #ffffff; } </style>