- 所需依赖 print-js(打印) jsbarcode(一维码)
- 普通打印功能
(1)index.vue
<template>
<div>
<button @click="print">打印</button>
<print-content v-show="showPrintContent" ref="printContentRef"/>
</div>
</template>
<script>
// 引入组件
import PrintContent from './PrintContent.vue'
export default {
components: {
PrintContent
},
data(){
return {
showPrintContent: false
}
},
methods: {
print(){
const that = this
that.showPrintContent = true
this.$nextTick(()=>{
that.$refs.printContentRef.print() // 调用子组件方法
})
}
}
}
</script>
PrintContent.vue组件
<template>
<div id="printBox">
打印内容
</div>
</template>
<script>
import printJS from 'print-js'
export default {
methods: {
print(){
printJS({
printable: 'printBox',
type: 'html',
scanStyles: false
})
}
}
}
</script>
3、分页功能 主要是添加style="page-break-after:always样式
<div id="printBox">
<div v-for="(item,index) in printData" :key="index" style="page-break-after:always">
{{item.value}}
</div>
</div>
</template>
<script>
import printJS from 'print-js'
export default {
data(){
return {
printData:[{
value: '第一页内容',
}, {
value: '第二页内容'
}]
}
},
methods: {
print(){
printJS({
printable: 'printBox',
type: 'html',
scanStyles: false
})
}
}
}
</script>
<style>
</style>
4、一维码打印功能
引入import JsBarcode from 'jsbarcode';
添加img控件
调用方法如下:
printBarcode(){
JsBarcode("#barcodeId", this.barcodeValue, {
format: "CODE128", //选择要使用的条形码类型
width: 1.5,//设置条之间的宽度
height: 50, //高度
displayValue: true, //是否在条形码下方显示文字
// text: "asd 2012101 血常规", //覆盖显示的文本
// fontOptions: "bold italic", //使文字加粗体或变斜体
// font: "fantasy", //设置文本的字体
// textAlign: "left", //设置文本的水平对齐方式
// textPosition: "top", //设置文本的垂直位置
textMargin: 1, //设置条形码和文本之间的间距
fontSize: 15, //设置文本的大小
// background: "#eee", //设置条形码的背景
lineColor: "#000", //设置条和文本的颜色。
margin: 10, //设置条形码周围的空白边距
});
}
5、最终结果
<template>
<div id="printBox">
<div v-for="(item,index) in printData" :key="index" style="page-break-after:always">
{{item.value}}
</div>
<img id="barcodeId"/>
</div>
</template>
<script>
import printJS from 'print-js'
import JsBarcode from 'jsbarcode';
export default {
data(){
return {
printData:[{
value: '第一页内容',
}, {
value: '第二页内容'
}],
barcodeValue: '1235456'
}
},
methods: {
printBarcode(){
JsBarcode("#barcodeId", this.barcodeValue, {
format: "CODE128", //选择要使用的条形码类型
width: 1.5,//设置条之间的宽度
height: 50, //高度
displayValue: true, //是否在条形码下方显示文字
// text: "asd 2012101 血常规", //覆盖显示的文本
// fontOptions: "bold italic", //使文字加粗体或变斜体
// font: "fantasy", //设置文本的字体
// textAlign: "left", //设置文本的水平对齐方式
// textPosition: "top", //设置文本的垂直位置
textMargin: 1, //设置条形码和文本之间的间距
fontSize: 15, //设置文本的大小
// background: "#eee", //设置条形码的背景
lineColor: "#000", //设置条和文本的颜色。
margin: 10, //设置条形码周围的空白边距
});
},
print(){
this.printBarcode()
printJS({
printable: 'printBox',
type: 'html',
scanStyles: false
})
}
}
}
</script>