- vue實現打印的兩種方法
- vue實現批量打印二維碼 (需安裝二維碼插件qrcodejs2)
一、vue-print-nb插件
1、安裝: npm i vue-print-nb -S
2、全局注冊(main.js):
import Print from 'vue-print-nb'
Vue.use(Print)
3、使用:
<div id="printTest" >
<p>鋤禾日當午</p>
<p>汗滴禾下土 </p>
<p>誰知盤中餐</p>
<p>粒粒皆辛苦</p>
</div>
<button v-print="'#printTest'">打印</button>
二、手動下載插件到本地
插件地址:https://github.com/xyl66/vuePlugs_printjs
1、在src下新建文件夾plugs,將下載好的print.js放入plugs文件夾下
2、全局注冊(main.js):
import Print from './plugins/print'
Vue.use(Print) // 注冊
3、使用
<div ref="print" >
<p>打印內容</p>
<p class="no-print">不要打印我</p>
</div>
<button @click="handlePrintText">打印</button>
<!--no-print樣式類 為不打印區域-->
methods:{
handlePrintText(){
this.$print(this.$refs.print)
}
}
實現批量打印二維碼
1、安裝二維碼插件
npm i qrcodejs2 -S
2、導入插件
import QRCode from 'qrcodejs2';
3、使用
<!--設置打印內容在頁面上不可見-->
<div style="display:none;">
<div ref="print" id="printStyle">
<div class="item" v-for="(item,index) in this.goodsData" :key="index">
<h2>{{item.name}}</h2>
<div class="qrcode-pic" ref=codeItem></div>
</div>
</div>
</div>
<button @click="handleBatchPrintCode">批量打印</button>
//假設需要批量打印的數組為goodsData:[{name:'商品1', code:'123'},{name:'商品2', code:'456'}]
methods:{
handleBatchPrintCode(){
//必須要等到頁面加載完成,不然會報錯
this.$nexTick(()=>{
this.goodsData.forEach((item,index)=>{
let code = item.code;
this.$refs.codeItem[index].innerHTML="";
new QRCode(this.$refs.codeItem[index], {
text: code, //二維碼內容
width: 200,
height: 200,
// colorDark: "#333333", //二維碼顏色
// colorLight: "#ffffff", //二維碼背景色
})
})
setTimeout(()=>{
this.$print(this.$refs.print);
},200)
})
}
}
4、樣式問題
//打印樣式放在這個里面就可以了
@media print{
#printStyle .item{
margin: 10px;
}
#printStyle h2{
font-size: 30px;
}
}
5、效果圖
這兩種方法效果一樣,點擊按鈕彈出一個打印彈窗,唯一不同的是調用方法不一樣,看個人需求選擇使用哪種
ps:功能算是實現了,具體還沒連打印機,所以沒法測試,有問題后面再補充