在el-image组件的预览中添加打印功能(自定义功能)

思路:给图片添加点击事件,通过js获取预览的工具栏,在工具栏中添加自定义按钮及事件

1、html 中 image标签

<el-image

style="width: 139px;

height: 89px"

:src="fileUrl"

:preview-src-list="fileUrl"

@click="handleImageClick(fileUrl)" //添加点击事件

/>

2、再点击事件中,通过js操作dom,添加自定义按钮事件

handleImageClick(fileUrl) {

this.$nextTick(() => {

const viewer = document.querySelector('.el-image-viewer__wrapper') //工具栏的dom

if (viewer) {

// 防止重复添加

if (!document.querySelector('.custom-print-btns')) {

const btn = document.createElement('button') //创建按钮

btn.className = 'custom-print-btns' //按需设计样式

btn.innerHTML = '<i class="el-icon-printer"></i>'

btn.onclick = () => this.printImage(fileUrl) //点击按钮触发事件

const btnGroup = viewer.querySelector('.el-image-viewer__actions__inner')

if (btnGroup) {

btnGroup.appendChild(btn) //在工具中添加按钮

}

}

}

})

},

3、添加后的图

4、打印事件

printImage(fileUrl) {

const printWindow = window.open('', '_blank')

printWindow.document.write(`

<html>

<head>

<title>打印图片</title>

<style>

body { text-align: center; margin: 0; padding: 0; }

img { max-width: 100%; max-height: 100vh; margin: auto; }

</style>

</head>

<body>

<img src="${fileUrl}" />

<script>

window.onload = function() {

setTimeout(function() {

window.print();

window.close();

}, 200);

}

<\/script>

</body>

</html>

`)

printWindow.document.close()

},

5、结果图

相关推荐
子兮曰4 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰4 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
前端小万4 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝4 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
A黄俊辉A4 天前
uniapp webview中实现 app和内嵌的H5双向通信
vue.js·json
三十而立洋4 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
卡布鲁4 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
李少兄4 天前
JavaScript 隐式全局变量解析
javascript
honkun64 天前
vue 表格组件 vxe-table 配置 ajax 请求自动加载数据与表单查询
vue.js·vxe-table
kybs19914 天前
全球灾害数据分析可视化 毕业设计-附源码66794
vue.js·spring boot·mysql·安全·django·c#·asp.net