vue实现模板打印
Vue 实现模板打印
在 Vue 中实现模板打印功能,通常需要结合浏览器的打印 API 和 CSS 打印样式。以下是几种常见的方法:
使用 window.print() 方法
创建一个打印按钮,点击时调用 window.print() 方法触发浏览器打印对话框。
<template>
<div>
<button @click="print">打印</button>
<div id="printArea">
<!-- 打印内容区域 -->
<h1>打印标题</h1>
<p>打印内容...</p>
</div>
</div>
</template>
<script>
export default {
methods: {
print() {
window.print();
}
}
};
</script>
<style>
@media print {
body * {
visibility: hidden;
}
#printArea, #printArea * {
visibility: visible;
}
#printArea {
position: absolute;
left: 0;
top: 0;
}
}
</style>
使用 vue-print-nb 插件
vue-print-nb 是一个 Vue 打印插件,使用起来更加方便。
安装插件:
npm install vue-print-nb --save
使用示例:
<template>
<div>
<button v-print="printObj">打印</button>
<div id="printContent">
<!-- 打印内容 -->
<h1>打印标题</h1>
<p>打印内容...</p>
</div>
</div>
</template>
<script>
import print from 'vue-print-nb'
export default {
directives: {
print
},
data() {
return {
printObj: {
id: 'printContent',
popTitle: '打印标题'
}
}
}
}
</script>
使用 CSS 控制打印样式
通过 CSS 的 @media print 可以控制打印时的样式,隐藏不需要打印的元素。
@media print {
.no-print {
display: none;
}
.print-only {
display: block;
}
}
动态生成打印内容
如果需要动态生成打印内容,可以使用 Vue 的模板和数据绑定。

<template>
<div>
<button @click="printReport">打印报表</button>
<div id="report" ref="report">
<h1>{{ title }}</h1>
<table>
<tr v-for="item in items" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.value }}</td>
</tr>
</table>
</div>
</div>
</template>
<script>
export default {
data() {
return {
title: '销售报表',
items: [
{ id: 1, name: '产品A', value: 100 },
{ id: 2, name: '产品B', value: 200 }
]
}
},
methods: {
printReport() {
const printWindow = window.open('', '', 'width=800,height=600')
printWindow.document.write('<html><head><title>打印</title></head><body>')
printWindow.document.write(this.$refs.report.innerHTML)
printWindow.document.write('</body></html>')
printWindow.document.close()
printWindow.focus()
printWindow.print()
printWindow.close()
}
}
}
</script>
注意事项
- 打印样式可能需要多次调试才能达到理想效果
- 某些浏览器可能会阻止弹出窗口,需要在用户交互事件中触发打印
- 复杂布局在打印时可能需要特殊处理
- 分页控制可以使用 CSS 的
page-break-before和page-break-after属性
以上方法可以根据具体需求选择使用,简单的打印需求使用 window.print() 配合 CSS 即可,复杂需求可以考虑使用打印插件或动态生成打印内容。






