vue实现打印表格
使用Vue实现表格打印功能
方法一:使用window.print()打印整个页面
在Vue组件中添加打印按钮,调用浏览器原生打印功能
<template>
<div>
<button @click="printTable">打印表格</button>
<table id="printable-table">
<!-- 表格内容 -->
</table>
</div>
</template>
<script>
export default {
methods: {
printTable() {
window.print();
}
}
}
</script>
<style>
@media print {
body * {
visibility: hidden;
}
#printable-table, #printable-table * {
visibility: visible;
}
#printable-table {
position: absolute;
left: 0;
top: 0;
}
}
</style>
方法二:使用iframe打印特定内容
创建一个iframe来加载需要打印的内容

printTable() {
const printContent = document.getElementById('printable-table').outerHTML;
const frame = document.createElement('iframe');
frame.style.position = 'absolute';
frame.style.width = '0';
frame.style.height = '0';
frame.style.border = 'none';
frame.onload = function() {
frame.contentWindow.focus();
frame.contentWindow.print();
document.body.removeChild(frame);
};
document.body.appendChild(frame);
frame.contentDocument.write(printContent);
frame.contentDocument.close();
}
方法三:使用打印专用CSS
为打印场景设计专门的样式

@media print {
.no-print {
display: none;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #000;
padding: 8px;
}
thead {
display: table-header-group;
}
tfoot {
display: table-footer-group;
}
}
方法四:使用第三方库vue-print-nb
安装并使用专门为Vue设计的打印插件
npm install vue-print-nb --save
import Print from 'vue-print-nb'
Vue.use(Print);
<template>
<div>
<button v-print="'#printable-table'">打印表格</button>
<table id="printable-table">
<!-- 表格内容 -->
</table>
</div>
</template>
方法五:处理分页打印
确保表格在打印时分页不会截断行
@media print {
table {
page-break-inside: auto;
}
tr {
page-break-inside: avoid;
page-break-after: auto;
}
thead {
display: table-header-group;
}
tfoot {
display: table-footer-group;
}
}
这些方法可以根据具体需求选择使用,从简单的原生打印到更复杂的第三方解决方案都能满足不同场景的需求。






