<template>
<div>
<!-- 打印内容区域 -->
<div ref="printContent" class="print-content">
<h2>打印内容标题</h2>
<p>这是要打印的内容...</p>
<table border="1" style="width: 100%">
<tr>
<th>项目</th>
<th>数量</th>
<th>价格</th>
</tr>
<tr>
<td>商品A</td>
<td>2</td>
<td>¥100</td>
</tr>
<tr>
<td>商品B</td>
<td>1</td>
<td>¥200</td>
</tr>
</table>
</div>
<!-- 打印按钮 -->
<button @click="handlePrint">打印内容</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
const printContent = ref(null);
const handlePrint = () => {
const printWindow = window.open('', '_blank');
printWindow.document.write(`
<html>
<head>
<title>打印</title>
<style>
body { font-family: Arial; margin: 20px; }
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
@media print {
.no-print { display: none !important; }
body { margin: 0; padding: 0; }
}
</style>
</head>
<body>
${printContent.value.innerHTML}
<script>
setTimeout(() => {
window.print();
window.close();
}, 100);
<\/script>
</body>
</html>
`);
printWindow.document.close();
};
</script>
<style scoped>
.print-content {
margin: 20px;
padding: 20px;
border: 1px solid #eee;
}
@media print {
.no-print {
display: none !important;
}
}
</style>