思路:给图片添加点击事件,通过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、结果图
