<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>
使用 CSS 媒体查询隐藏非打印内容
<template>
<div>
<!-- 不打印的内容 -->
<div class="no-print">
<h1>网页标题</h1>
<nav>导航菜单...</nav>
</div>
<!-- 打印内容 -->
<div class="printable-area">
<h2>订单详情</h2>
<p>订单号: 123456789</p>
<!-- 更多打印内容... -->
</div>
<button @click="printPage" class="no-print">打印页面</button>
</div>
</template>
<script setup>
const printPage = () => {
window.print();
};
</script>
<style>
/* 普通样式 */
.no-print {
padding: 20px;
background-color: #f5f5f5;
}
.printable-area {
padding: 20px;
margin: 20px 0;
border: 1px dashed #ccc;
}
/* 打印样式 */
@media print {
.no-print {
display: none;
}
.printable-area {
border: none;
padding: 0;
margin: 0;
}
body {
font-size: 12pt;
line-height: 1.5;
}
}
</style>