目录
1.window.print()
2.使用插件print.js
1.window.print()
<template>
<div id="contenteBox">内容</div>
<button @click="printContent">打印</button>
</template>
<script>
export default{
data(){
return{}
},
methods:{
printContent(){
let contentDom=document.getElementById('contenteBox')
let html=`
<head>
<style lang='scss'>
#contenteBox{font-size:18px;background-color:#333}
<style>
</head>
<body>${contentDom.innerHTML}</body>
`
window.print()
}
}
}
</script>
let contentDom=document.getElementById('contenteBox') //获取id为contenteBox的dom元素
window.print() //打印
也可以let bodyContent = document.getElementById('contenteBox').innerHTML 通过 获取需要打印的元素
通过 document.body.innerHTML=bodyContent 把当前页面替换为打印内容HTML
window.print()打印 //记得最后还原页面
2.使用插件print.js
2.1 vue2
https://www.npmjs.com/package/print-js
npm install print-js --saveyarn add print-jsimport printJS from 'print-js'
<template><div><button @click="printContent">打印</button><div id="contenBox"><div>内容</div></div></div>
</template><script>
import printJS from 'print-js';export default {methods: {printContent() {printJS({printable: 'contenBox',type: 'html',documentTitile:'打印',style: `#contenBox{color:#333,font-size:20px}`});}}
};
</script>
printable 文档来源
type 打印类型
documentTitle 打印显示的文档标题
style 自定义样式
2.2 vue3
<template><div><button @click="printContent">打印</button><div ref="contenBox"><div>内容</div></div></div>
</template><script>
import printJS from 'print-js';
let contenBox=ref()
function printContent() {printJS({printable: 'contenBox',type: 'html',documentTitile:'打印',style: `#contenBox{color:#333,font-size:20px}`});}
</script>