vue实现发票预览
Vue 实现发票预览功能
发票预览功能通常需要结合数据展示、样式设计和打印功能。以下是实现步骤:
设计发票模板
使用 Vue 的模板语法设计发票的 HTML 结构,确保布局清晰且符合发票规范:
<div class="invoice-preview">
<div class="invoice-header">
<h2>发票抬头</h2>
<p>发票编号: {{ invoiceData.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 invoiceData.items" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.quantity }}</td>
<td>{{ item.price }}</td>
<td>{{ item.quantity * item.price }}</td>
</tr>
</tbody>
</table>
</div>
<div class="invoice-footer">
<p>总计: {{ totalAmount }}</p>
</div>
</div>
绑定动态数据
通过 Vue 的 data 或 props 绑定发票数据:
data() {
return {
invoiceData: {
number: 'INV20230001',
items: [
{ id: 1, name: '商品A', quantity: 2, price: 100 },
{ id: 2, name: '商品B', quantity: 1, price: 200 }
]
}
};
},
computed: {
totalAmount() {
return this.invoiceData.items.reduce((sum, item) => sum + item.quantity * item.price, 0);
}
}
添加打印功能
使用 window.print() 实现打印预览,并通过 CSS 控制打印样式:

methods: {
printInvoice() {
window.print();
}
}
在 CSS 中添加打印样式:
@media print {
body * {
visibility: hidden;
}
.invoice-preview, .invoice-preview * {
visibility: visible;
}
.invoice-preview {
position: absolute;
left: 0;
top: 0;
width: 100%;
}
}
使用第三方库增强功能
如需更复杂的表格或 PDF 导出功能,可以集成以下库:

- html2pdf.js:将 HTML 转换为 PDF。
- vue-html-to-paper:专为 Vue 设计的打印插件。
安装并调用示例:
import html2pdf from 'html2pdf.js';
methods: {
exportToPDF() {
const element = document.querySelector('.invoice-preview');
html2pdf().from(element).save('invoice.pdf');
}
}
响应式设计
通过 CSS 确保发票在不同设备上显示正常:
.invoice-preview {
width: 100%;
max-width: 800px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ddd;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
完整示例代码
以下是一个完整的 Vue 单文件组件示例:
<template>
<div>
<div class="invoice-preview" ref="invoiceContent">
<!-- 发票模板内容 -->
</div>
<button @click="printInvoice">打印</button>
<button @click="exportToPDF">导出PDF</button>
</div>
</template>
<script>
import html2pdf from 'html2pdf.js';
export default {
data() {
return {
invoiceData: {
// 数据示例
}
};
},
methods: {
printInvoice() {
window.print();
},
exportToPDF() {
const element = this.$refs.invoiceContent;
html2pdf().from(element).save();
}
}
};
</script>
<style>
/* 样式内容 */
</style>






