vue3 前端打印功能主要通过插件来实现。
市面上常用的有 vue3-print-nb 、print-js 等插件。
下载安装
npm i vue3-print-nb --save
main.js 全局配置
import { createApp } from "vue";
import { createPinia } from "pinia";
import "./style.css";
import App from "./App.vue";
import router from "./router";
import print from 'vue3-print-nb'
import ElementPlugin from "./plugins/element";
const app = createApp(App);
app.use(createPinia());
app.use(ElementPlugin);
app.use(router);
app.use(print);//打印
app.mount("#app");
设置打印区域
<div id="printData">
<el-table border :data="tableData" style="width: 100%">
<el-table-column prop="date" label="Date" width="180" />
<el-table-column prop="name" label="Name" width="180" />
<el-table-column prop="address" width="180" label="Address" />
</el-table>
</div>
完整代码:
<template>
<div>
<el-card>
<template #header>
<el-button v-print="print" type="success"
>点击打印</el-button
>
</template
>
<div id="printData">
<el-table border :data="tableData" style="width: 100%">
<el-table-column
prop="date"
label="Date"
width="180"
/>
<el-table-column
prop="name"
label="Name"
width="180"
/>
<el-table-column
prop="address"
width="180"
label="Address"
/>
</el-table
>
</div>
</el-card
>
</div>
</template>
<script setup lang="ts">
const tableData = [
{
date: "2024-05-03",
name: "张三",
address: "北京",
},
{
date: "2024-09-02",
name: "李四",
address: "上海",
},
]
// 打印
const print = {
id: "printData",
popTitle: "打印数据",
}
</script>
<style lang="scss" scoped>
@page {
size: auto;
margin-bottom: 5mm;
}
</style>