利用Vue实现打印功能
Author:kak
- 记录型文章
1、 打印指定区域
npm install vue-print-nb --save
//安装好以后在main.js文件中引入
import Print from 'vue-print-nb'
Vue.use(Print); //注册
<div id="printTest" >
需要打印的区域
</div>
<el-button type="success" v-print="'#printTest'" id="noprint">打印整个div</el-button>
2、 调出当前页面打印,去除不需要的
template中
<el-button type="success" @click="print">打印全局</el-button>
js中
methods: {
print() {
window.print(); // 打印
},
},
style中
@media print{
.noprint{ //不打印的部分,隐藏起来
display:none;
}
.print{ //要打印的部分,显示
display:block;
}
}
3、完整代码
<template>
<div>
<div class="buttonStyle" id="noprint">
<el-button type="primary" @click="addView()">添加学生信息</el-button>
</div>
<div id="printTest">
<el-table
:data="students"
:header-cell-style="{
background: '#E7F4FF',
color: '#000',
'font-weight': '700',
}"
border
stripestyle="width: 100%"
>
<el-table-column
prop="ownCode"
label="学生ID"
align="center"
width="200px"
></el-table-column>
<el-table-column
prop="phone"
label="手机号"
align="center"
></el-table-column>
<el-table-column
prop="name"
label="学生姓名"
align="center"
></el-table-column>
<el-table-column
prop="sex"
label="学生性别"
align="center"
width="100px"
></el-table-column>
<el-table-column
prop="age"
label="学生年龄"
align="center"
></el-table-column>
<el-table-column
prop="enabled"
label="学生状态"
align="center"
width="100px"
>
<template slot-scope="scope">
<el-tag size="small" v-if="scope.row.enabled == 'Y'" effect="plain"
>生效</el-tag
>
<el-tag
size="small"
v-if="scope.row.enabled == 'N'"
effect="plain"
type="danger"
>失效</el-tag
>
</template>
</el-table-column>
<el-table-column label="操作" align="center">
<template slot-scope="scope">
<el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
>修改</el-button
>
<el-button
size="mini"
type="danger"
@click="handleDelete(scope.$index, scope.row)"
>删除</el-button
>
</template>
</el-table-column>
</el-table>
</div>
<el-button type="success" v-print="'#printTest'" id="noprint">打印整个div</el-button>
<el-button type="success" @click="print">打印全局</el-button>
</div>
</template>
<script>
export default {
data() {
return {
dialogFormVisible: false,
dialogFormVisible1: false,
formLabelWidth: "120px",
student: {
ownCode: "",
name: "",
sex: "",
pwd: "",
phone: "",
age: "",
enabled: "",
},
students: [],
search: "",
};
},
// 页面加载时触发
created() {
this.$axios
.get("studentList", {})
.then((response) => {
console.log(response);
if (response.data.statusCode == 200) {
this.students = response.data.data;
}
})
.catch((error) => {
alert(error);
});
},
methods: {
print() {
window.print(); // 打印
},
},
};
</script>
<style scoped>
.buttonStyle {
float: left;
margin-top: -12px;
}
@media print {
#noprint {
display: none;
}
.print {
display: block;
}
}
</style>