- 最近,项目中用到打印表格的需求,在网上找了好些都不太行,不是样式缺少,就是内容缺少,基本思路还是调用window自带的print功能。
我用el-ui自带的表格,打印的时候样式内容都有一定的缺少,能成功的小伙伴们分享下,下面是我用原生写的实现了。 - 表格如下
<template>
<div :id="`printJS-html`">
<table cellpadding="0" cellspacing="0" style="width: 1260px">
<tr> // 这里是表头
<th>考评项目</th>
<th>考评内容</th>
<th>分值</th>
<th>考评标准</th>
</tr>
// 下面双循环拿数据渲染
<template v-for="(item, index) in groupListTableJD">
<tr>
// 第一列都是考评项目
<td v-if="index == 0" :rowspan="groupListTableJD.length" >
{{ groupListTableJD[0].type_name }}
</td>
<td>{{ item.norm_name }}</td>
<td>{{ item.norm_score }}</td>
// 按需
<div
v-for="(curr, ix) in item.deduction"
:class="['contentTableCell']"
>
{{ curr.score_name }}
</div>
</tr>
</template>
</table>
</div>
</template>
<script>
export default {
components: {},
props: {
groupListTableJD: {
type: Object,
default: {},
},
},
data() {
return {};
},
methods: {
onPrint() {
printJS({
printable: `printJS-html`,
type: "html",
targetStyles: ["*"],
});
},
},
};
</script>
// 样式就不写了
可以把上面这个demo作为子组件,哪里需要引入即可,groupListTableJD 为父组件传入的数据,然后在父组件中定义按钮
<el-button
class="back-info"
type="danger"
icon="el-icon-document-copy"
@click="print"
style="margin-bottom: 10px !important"
>打 印</el-button
>
<Print ref="table" :groupListTableJD="groupListTableJD" ></Print>
点击按钮,
import Print from 'xxxxx' // 刚刚自定义的子组件路径
export default {
name: "basetable",
components:{
Print
},
data(){
return{
groupListTableJD = [
{
check_object: "部门人员",
check_object_id: 347,
deduction: [{ id: 45, score_name: "3324" }],
id: 66,
norm_name: "测试",
norm_score: 30,
title: "xxx市场监督管理局",
type_dic: 1,
type_name: "管理服务",
},
{
check_object: "部门人员",
check_object_id: 347,
deduction: [{ id: 30, score_name: "台面清洁度" }, { id: 31, score_name: "台面整洁度" }],
id: 67,
norm_name: "台面考核",
norm_score: 10,
title: "xxx市场监督管理局",
type_dic: 1,
type_name: "管理服务",
},
{
check_object: "市场人员",
check_object_id: 348,
deduction: [{ id: 32, score_name: "服装干净" }, { id: 33, score_name: "服装统一" }],
id: 68,
norm_name: "市场服装",
norm_score: 10,
title: "xxx市场监督管理局",
type_dic: 1,
type_name: "管理服务",
},
{
check_object: "市场人员",
check_object_id: 348,
deduction: [{ id: 44, score_name: "考评标准1" }],
id: 72,
norm_name: "测试测试",
norm_score: 50,
title: "xxx市场监督管理局",
type_dic: 1,
type_name: "管理服务",
}
]
}
}
methods:{
print(){
this.$refs.table.onPrint();
},
}