vue实现动态打印
Vue 实现动态打印的方法
使用 window.print() 方法
在 Vue 中可以通过调用 window.print() 方法触发浏览器的打印功能。这种方法简单直接,适合打印整个页面或特定区域。
<template>
<div>
<button @click="printPage">打印页面</button>
<div ref="printContent">需要打印的内容</div>
</div>
</template>
<script>
export default {
methods: {
printPage() {
window.print();
}
}
};
</script>
打印特定区域
如果需要打印页面中的特定区域,可以通过 CSS 控制打印内容的显示和隐藏。
<template>
<div>
<button @click="printSpecificArea">打印特定区域</button>
<div class="no-print">不需要打印的内容</div>
<div class="print-only">需要打印的内容</div>
</div>
</template>
<style>
@media print {
.no-print {
display: none;
}
.print-only {
display: block;
}
}
</style>
使用第三方库 vue-print-nb
vue-print-nb 是一个专门为 Vue 设计的打印插件,可以更方便地控制打印内容和样式。
安装:
npm install vue-print-nb --save
使用:
<template>
<div>
<button v-print="printObj">打印</button>
<div id="printContent">需要打印的内容</div>
</div>
</template>
<script>
import print from 'vue-print-nb';
export default {
directives: {
print
},
data() {
return {
printObj: {
id: 'printContent',
popTitle: '打印标题'
}
};
}
};
</script>
动态生成打印内容
如果需要动态生成打印内容,可以通过数据绑定和模板渲染实现。
<template>
<div>
<button @click="printDynamicContent">打印动态内容</button>
<div ref="dynamicContent">
<p v-for="item in items" :key="item.id">{{ item.text }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, text: '内容1' },
{ id: 2, text: '内容2' }
]
};
},
methods: {
printDynamicContent() {
const printWindow = window.open('', '_blank');
printWindow.document.write(`
<html>
<head>
<title>打印内容</title>
</head>
<body>
${this.$refs.dynamicContent.innerHTML}
</body>
</html>
`);
printWindow.document.close();
printWindow.print();
}
}
};
</script>
打印样式控制
通过 CSS 的 @media print 可以控制打印时的样式,例如隐藏按钮、调整字体大小等。
<style>
@media print {
button {
display: none;
}
body {
font-size: 12pt;
}
}
</style>
打印 PDF
如果需要将内容打印为 PDF,可以使用 html2pdf.js 库。
安装:
npm install html2pdf.js --save
使用:
<template>
<div>
<button @click="printPDF">打印为PDF</button>
<div ref="pdfContent">需要打印为PDF的内容</div>
</div>
</template>
<script>
import html2pdf from 'html2pdf.js';
export default {
methods: {
printPDF() {
const element = this.$refs.pdfContent;
const opt = {
margin: 1,
filename: 'document.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
};
html2pdf().from(element).set(opt).save();
}
}
};
</script>
以上方法可以根据具体需求选择适合的方式实现动态打印功能。







