vue实现打印预览功能
使用vue-print-nb插件实现打印预览
安装vue-print-nb插件:
npm install vue-print-nb --save
在main.js中引入并注册:
import Print from 'vue-print-nb'
Vue.use(Print)
在组件中使用:
<template>
<div id="printContent">
<!-- 需要打印的内容 -->
<h1>打印测试</h1>
<p>这是要打印的内容</p>
</div>
<button v-print="printObj">打印</button>
</template>
<script>
export default {
data() {
return {
printObj: {
id: 'printContent',
popTitle: '打印标题', // 打印窗口标题
extraCss: 'https://example.com/style.css' // 额外CSS
}
}
}
}
</script>
使用window.print原生方法实现
创建打印方法:
methods: {
handlePrint() {
const printContent = document.getElementById('printContent').innerHTML
const originalContent = document.body.innerHTML
document.body.innerHTML = printContent
window.print()
document.body.innerHTML = originalContent
}
}
添加打印按钮:
<template>
<div id="printContent">
<!-- 打印内容 -->
</div>
<button @click="handlePrint">打印</button>
</template>
使用CSS控制打印样式
添加打印专用样式:
@media print {
body * {
visibility: hidden;
}
#printContent, #printContent * {
visibility: visible;
}
#printContent {
position: absolute;
left: 0;
top: 0;
width: 100%;
}
}
使用iframe实现打印预览
创建iframe打印方法:
printWithIframe() {
const content = document.getElementById('printContent').innerHTML
const iframe = document.createElement('iframe')
document.body.appendChild(iframe)
iframe.contentDocument.write(content)
iframe.contentDocument.close()
iframe.contentWindow.focus()
iframe.contentWindow.print()
setTimeout(() => {
document.body.removeChild(iframe)
}, 100)
}
注意事项
打印内容中避免使用浮动元素和绝对定位,可能导致打印布局问题
对于复杂表格,建议使用专门的打印样式表控制显示
测试不同浏览器的打印效果,Chrome和Firefox可能存在差异
批量打印时考虑使用队列机制,避免打印窗口被拦截







