Vue3实现打印功能
1、安装插件
npm i vue3-print-nb --save
2、main.js全局配置
import print from 'vue3-print-nb'
app.use(print)
3、设置打印区域
为打印区域设置 id 选择器
<div id="printData">
<el-table border :data="tableData" style="width: 100%">
<el-table-column prop="date" label="Date" width="180" />
<el-table-column prop="name" label="Name" width="180" />
<el-table-column prop="address" width="180" label="Address" />
</el-table>
</div>
4、绑定打印事件
为打印按钮绑定 v-print
<el-button v-print="print" type="success">点击打印</el-button>
// 打印
const print = {
id: "printData",
popTitle: "打印数据",
};
5、完整代码
<template>
<div>
<el-card>
<template #header>
<el-button v-print="print" type="success">点击打印</el-button>
</template>
<div id="printData">
<el-table border :data="tableData" style="width: 100%">
<el-table-column prop="date" label="Date" width="180" />
<el-table-column prop="name" label="Name" width="180" />
<el-table-column prop="address" width="180" label="Address" />
</el-table>
</div>
</el-card>
</div>
</template>
<script setup>
const tableData = [
{
date: "2024-05-03",
name: "知否君",
address: "中国北京",
},
{
date: "2024-05-02",
name: "工藤新一",
address: "中国上海",
},
];
// 打印
const print = {
id: "printData",
popTitle: "打印数据",
};
</script>
<style lang="scss" scoped>
@page {
size: auto;
margin-bottom: 5mm;
}
</style>
6、解决打印表格无边框
使用原生table
<div id="printData">
<table class="printTable" border="1">
<thead>
<tr>
<th>姓名</th>
<th>生日</th>
<th>地址</th>
</tr>
</thead>
<tbody>
<tr>
<td>张三</td>
<td>1998-02-25</td>
<td>河北避暑山庄</td>
</tr>
<tr>
<td>李四</td>
<td>1996-02-24</td>
<td>北京大兴</td>
</tr>
<tr>
<td>王五</td>
<td>1997-02-26</td>
<td>浙江杭州</td>
</tr>
</tbody>
</table>
</div>
.printTable {
color: #616161;
width: 100%;
border-collapse: collapse;
border: 0.25px solid #ededed;
text-align: left;
font-size: 15px;
th,
td {
padding: 6px;
}
}
7、解决单选框复选框打印不选中
@media print {
::v-deep .el-radio__input,
::v-deep .el-checkbox__input {
-webkit-print-color-adjust: exact;
-moz-print-color-adjust: exact;
color-adjust: exact;
}
}
8、去除页脚页眉
@page {
size: auto;
margin: 0mm;
}
9、解决打印內容不自动换行
word-wrap:break-word;