uniapp写一个页面打印的代码
时间: 2023-12-26 18:04:12 浏览: 77
以下是一个使用uniapp框架编写的打印页面的示例代码:
<template>
<div class="print-page">
<div class="print-content">
<!-- 打印内容 -->
<h1>打印页面的标题</h1>
<p>打印页面的内容</p>
</div>
<div class="print-btn" @click="printPage()">打印页面</div>
</div>
</template>
<script>
export default {
methods: {
printPage() {
// 创建一个新的窗口
const printWindow = window.open('', 'PrintWindow', 'height=400,width=600');
// 获取打印内容
const printContent = document.querySelector('.print-content').innerHTML;
// 将打印内容写入新窗口中
printWindow.document.write(printContent);
// 执行打印命令
printWindow.print();
// 关闭新窗口
printWindow.close();
}
}
}
</script>
<style>
.print-page {
display: flex;
flex-direction: column;
align-items: center;
}
.print-content {
margin: 20px;
padding: 20px;
border: 1px solid #ccc;
}
.print-btn {
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
cursor: pointer;
}
</style>
在上面的代码中,我们创建了一个打印页面的模板,包括打印内容和一个打印按钮。在打印按钮的点击事件中,我们使用window.open()方法创建了一个新的窗口,将打印内容写入新窗口中,并执行打印命令,最后关闭新窗口。通过这种方式,我们可以实现在浏览器中打印页面的功能。