vue3 自定义事件 打印网页

本文介绍了如何在Vue.js项目中使用html2canvas和print-js库,创建了一个printModal指令,实现点击按钮时可以下载弹窗内容为图片或进行打印,提供了两种不同模式的el-button示例。

1.在main.ts中
 

// npm install --save html2canvas
//npm install print-js --save

import html2canvas from 'html2canvas';
import printJS from 'print-js'
const app = createApp(App);

// 全部打印自定义
app.directive('printModal', {
    mounted(el, binding) {
        el.addEventListener('click', async () => {
            const modal = document.querySelector('.modal'); // 选择你要截取的弹窗元素  
            const canvas = await html2canvas(modal); // 将弹窗内容转换为图片  
            const image = canvas.toDataURL('image/png'); // 将图片转换为Data URL
            if (binding.value == 1) {
                printJS({
                    printable: image,
                    type: 'image',
                    documentTitle: '',
                    imageStyle: 'width:100%;'
                })
            } else {
                const a = document.createElement('a');
                a.href = image;
                a.download = '图片';
                a.click();
            }
        });
    }
});

2.使用

        <el-button type="primary" v-print-modal="0">下载</el-button>
        <el-button type="primary" v-print-modal="1">打印</el-button>

Vue3 中实现预览打印功能通常需要结合 HTML 的 `print` API 和样式控制来完成。以下是实现的基本步骤: --- ### 实现思路 #### 1. 使用 CSS 控制页面布局 通过指定媒体查询 `@media print {}` 来调整页面在打印模式下的显示效果。例如隐藏不必要的元素、设置字体大小等。 ```css @media print { body * { visibility: hidden; } #print-section, #print-section * { visibility: visible; } #print-section { position: absolute; left: 0; top: 0; } } ``` 上述代码表示,在打印时只显示 ID 为 `#print-section` 的内容,其他部分会被隐藏。 --- #### 2. Vue 组件中动态生成打印内容 可以在 Vue 模板中创建一个专门用于打印的内容区域,并根据需求填充数据。 示例代码: ```vue <template> <div id="app"> <!-- 显示区 --> <button @click="handlePrint">打印预览</button> <!-- 打印专用区 (默认隐藏) --> <div id="print-section" style="display:none;"> <h1>这是要打印的内容标题</h1> <p>{{ content }}</p> </div> </div> </template> <script> export default { data() { return { content: "这是一个示例文本", }; }, methods: { handlePrint() { // 切换打印区域可见性并触发浏览器打印功能 const printSection = document.getElementById("print-section"); printSection.style.display = "block"; window.print(); // 防止影响正常页面显示,重新隐藏打印区域 setTimeout(() => { printSection.style.display = "none"; }, 50); }, }, }; </script> ``` --- #### 3. 调用 `window.print()` 触发打印窗口 当用户点击“打印”按钮时,会触发展开原生的打印机选择界面。注意这里的打印行为不会直接将内容发送到打印机上,而是允许用户手动确认后再提交给设备。 --- ### 总结 以上就是在 Vue3 环境下利用 JavaScript 及 CSS 完成简单网页局部内容打印的一个完整案例。实际项目里还可以进一步优化用户体验比如添加更多自定义选项或是改善视觉呈现等方面的工作。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值