vue实现局部打印
使用vue-print-nb插件实现局部打印
安装vue-print-nb插件
npm install vue-print-nb --save
在main.js中引入并注册插件
import Print from 'vue-print-nb'
Vue.use(Print)
在组件中使用v-print指令
<template>
<div id="printArea">
<!-- 需要打印的内容 -->
</div>
<button v-print="printObj">打印</button>
</template>
<script>
export default {
data() {
return {
printObj: {
id: 'printArea',
popTitle: '打印标题' // 打印时显示的标题
}
}
}
}
</script>
使用window.print()方法实现局部打印
创建打印样式
<style>
@media print {
body * {
visibility: hidden;
}
#printArea, #printArea * {
visibility: visible;
}
#printArea {
position: absolute;
left: 0;
top: 0;
}
}
</style>
添加打印按钮和打印区域
<template>
<div id="printArea">
<!-- 需要打印的内容 -->
</div>
<button @click="printContent">打印</button>
</template>
<script>
export default {
methods: {
printContent() {
window.print()
}
}
}
</script>
使用iframe实现局部打印
创建打印方法
printByIframe(content) {
const iframe = document.createElement('iframe')
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;')
document.body.appendChild(iframe)
const doc = iframe.contentWindow.document
doc.write(content)
doc.close()
iframe.contentWindow.focus()
iframe.contentWindow.print()
setTimeout(() => {
document.body.removeChild(iframe)
}, 100)
}
在组件中使用
<template>
<div ref="printContent">
<!-- 需要打印的内容 -->
</div>
<button @click="handlePrint">打印</button>
</template>
<script>
export default {
methods: {
handlePrint() {
const content = this.$refs.printContent.innerHTML
this.printByIframe(content)
}
}
}
</script>
使用CSS媒体查询优化打印效果
添加专门的打印样式
@media print {
@page {
size: A4;
margin: 0;
}
body {
padding: 1cm;
font-size: 12pt;
line-height: 1.5;
}
.no-print {
display: none !important;
}
.page-break {
page-break-after: always;
}
}
注意事项
打印内容中避免使用背景色和背景图片,大多数浏览器默认不打印背景
对于表格等需要分页的内容,使用CSS控制分页
table {
page-break-inside: avoid;
}
打印前可以添加loading状态,避免内容未完全渲染就开始打印
对于动态内容,确保数据加载完成后再触发打印操作







