vue实现发票预览
Vue 实现发票预览功能
在 Vue 中实现发票预览功能,通常需要结合数据渲染、样式设计和打印功能。以下是实现发票预览的几种方法:
数据绑定与模板设计
使用 Vue 的模板语法和数据绑定功能来设计发票的 HTML 结构。发票数据可以通过 props 或 Vuex 状态管理传递到预览组件。例如:
<template>
<div class="invoice-preview">
<div class="invoice-header">
<h2>{{ invoice.title }}</h2>
<p>发票编号: {{ invoice.number }}</p>
</div>
<div class="invoice-body">
<table>
<thead>
<tr>
<th>项目</th>
<th>数量</th>
<th>单价</th>
<th>金额</th>
</tr>
</thead>
<tbody>
<tr v-for="item in invoice.items" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.quantity }}</td>
<td>{{ item.price }}</td>
<td>{{ item.total }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
样式设计与打印优化
发票预览的样式需要特别注意打印时的表现。使用 CSS 的 @media print 规则来优化打印效果:
.invoice-preview {
width: 210mm;
margin: 0 auto;
padding: 20px;
background: white;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
@media print {
body * {
visibility: hidden;
}
.invoice-preview, .invoice-preview * {
visibility: visible;
}
.invoice-preview {
position: absolute;
left: 0;
top: 0;
width: 100%;
box-shadow: none;
}
}
打印功能实现
在 Vue 组件中添加打印方法,调用浏览器的打印 API:
methods: {
printInvoice() {
window.print();
}
}
PDF 生成与下载
如果需要生成 PDF 文件,可以使用库如 html2pdf.js 或 jspdf:
import html2pdf from 'html2pdf.js';
methods: {
generatePDF() {
const element = document.getElementById('invoice-preview');
const opt = {
margin: 10,
filename: 'invoice.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
};
html2pdf().from(element).set(opt).save();
}
}
动态数据加载
如果发票数据需要从后端 API 加载,可以在组件的 created 或 mounted 钩子中发起请求:
data() {
return {
invoice: {}
};
},
async created() {
const response = await axios.get('/api/invoice/123');
this.invoice = response.data;
}
响应式设计
确保发票预览在不同设备上都能正常显示,可以使用响应式 CSS 框架如 Bootstrap 或 TailwindCSS:
<div class="container mx-auto px-4">
<div class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
<!-- 发票内容 -->
</div>
</div>
通过以上方法,可以在 Vue 中实现功能完善、样式美观且支持打印的发票预览功能。根据实际需求,可以选择适合的技术方案进行组合和扩展。







