vue实现填写打印功能
使用Vue实现填写打印功能
在Vue中实现填写打印功能通常涉及表单数据的绑定和打印样式的控制。以下是几种常见的方法:
使用window.print()方法
创建一个专门用于打印的组件或页面,通过window.print()触发浏览器打印功能。

<template>
<div>
<div class="print-content" ref="printContent">
<h1>{{ formData.title }}</h1>
<p>{{ formData.content }}</p>
</div>
<button @click="handlePrint">打印</button>
</div>
</template>
<script>
export default {
data() {
return {
formData: {
title: '打印测试',
content: '这是要打印的内容'
}
}
},
methods: {
handlePrint() {
window.print()
}
}
}
</script>
<style>
@media print {
body * {
visibility: hidden;
}
.print-content, .print-content * {
visibility: visible;
}
.print-content {
position: absolute;
left: 0;
top: 0;
}
}
</style>
使用vue-print-nb插件
vue-print-nb是一个专门为Vue设计的打印插件,使用更简单。

npm install vue-print-nb --save
<template>
<div>
<div id="printMe">
<h1>{{ title }}</h1>
<p>{{ content }}</p>
</div>
<button v-print="'#printMe'">打印</button>
</div>
</template>
<script>
import print from 'vue-print-nb'
export default {
directives: {
print
},
data() {
return {
title: '打印测试',
content: '使用vue-print-nb插件打印'
}
}
}
</script>
使用iframe实现打印
对于更复杂的打印需求,可以使用iframe来加载打印内容。
<template>
<div>
<textarea v-model="content"></textarea>
<button @click="printIframe">打印</button>
<iframe ref="printFrame" style="display:none"></iframe>
</div>
</template>
<script>
export default {
data() {
return {
content: '要打印的内容'
}
},
methods: {
printIframe() {
const iframe = this.$refs.printFrame
const doc = iframe.contentDocument || iframe.contentWindow.document
doc.open()
doc.write(`
<!DOCTYPE html>
<html>
<head>
<title>打印内容</title>
<style>
body { font-family: Arial; }
</style>
</head>
<body>
${this.content}
</body>
</html>
`)
doc.close()
iframe.contentWindow.focus()
iframe.contentWindow.print()
}
}
}
</script>
打印样式优化
在CSS中使用@media print规则可以优化打印效果。
@media print {
body {
margin: 0;
padding: 0;
background: white;
}
.no-print {
display: none;
}
.page-break {
page-break-after: always;
}
}
注意事项
- 打印前确保所有动态内容已加载完成
- 对于分页需求,使用CSS的page-break属性
- 测试不同浏览器的打印兼容性
- 考虑添加打印按钮的权限控制
- 对于大量数据,考虑分批次打印
以上方法可以根据具体需求选择使用,简单的打印需求使用window.print()即可,复杂的打印布局建议使用专门的打印插件或iframe方案。






