使用print-js
//安装print-js
npm install print-js --save
//引用
import print from 'print-js'
打印指定区域
<div id="custom">需要打印的内容</div>
<button type="primary" @click="handlePrint">打印</button>
handlePrint() {
const style = "@page {margin:0 10mm};"; //打印时去掉眉页眉尾
//打印为什么要去掉眉页眉尾?因为眉页title时打印当前页面的title,相当于是获取html中title标签里面的内容,但是比如我打印的内容只是一个弹框里面的内容,是没有title的,这时候就会出现undefined,为了避免出现这种情况,就可以隐藏眉页眉尾
printJS({
printable: "custom", // 标签元素id
type: "html",//打印的类型
targetStyles: ["*"],// 在打印HTML元素时处理任何样式
});
},
打印json数据
<button type="button" onclick="printJS({
printable: data,
properties: ['name', 'email', 'phone'],
type: 'json',
gridHeaderStyle: 'color: red; border: 2px solid #3971A5;',
gridStyle: 'border: 2px solid #3971A5;'
})">
打印json数据
</button>
export default {
data() {
return {
data = [
{
name: 'John Doe',
email: 'john@doe.com',
phone: '111-111-1111'
},
{
name: 'Barry Allen',
email: 'barry@flash.com',
phone: '222-222-2222'
},
{
name: 'Cool Dude',
email: 'cool@dude.com',
phone: '333-333-3333'
}
]
};
},
}
效果图