一切問題存在時,都比想得困難嫁佳,解決了都比想得簡單
記錄一下當時遇到的問題:
1挨队,開始調打印機的時候,數據是寫死的所有蒿往,直接調用打印機就打印出來了盛垦。但是當我獲取后端返回來的數據時,只能獲取到寫的死數據瓤漏。
死數據當時調用寫法(不做參考腾夯,只是為了本人記錄)
例如:
<div id="qrCode" ref='printModel' class="modelPrint">
<div style="page-break-after:always;"><!--page-break-after:always;這個是分頁符,就是打印很多張的時候蔬充,為了確保每張顯示的內容-->
<div style="width: 450px;padding: 0px 20px;margin-top:12px;">
<div style="text-align: center;font-weight: 700;">產品合格證名稱</div>
<div style="display: flex;align-items: center; padding-left: 15px;">
<div style="text-align: center;">
<div style="margin-left: 15px;font-size: 14px;padding-right: 4px;">
<p style="margin-bottom:0px;margin-top:7px;">產品名稱: 獼猴挑</p>
<p style="margin-bottom: 2px;margin-top:7px;">生產批次: 123443522</p>
<p style="margin-bottom: 2px;margin-top:7px;">開證日期: 2020.05.15 12:20:40</p>
<p style="margin-bottom: 2px;margin-top:7px;">生產廠家: 實質性</p>
</div>
<p style="margin-bottom: 2px;margin-top:7px;">追 溯 碼: 29128384392</p>
</div>
</div>
<div style="text-align: center; font-weight: 700;margin-top: 3px;">[生產經營主體對追溯信息真實性負責]</div>
</div>
</div>
</div>
<button @click=‘print’>打印</button>
methods方法
print(){
var newWin = window.open("") // 新打開一個空窗口
this.imageToPrint = document.getElementById('qrCode') // 將要被打印的內容(特別注意這個獲取方式)
newWin.document.write(this.imageToPrint.outerHTML) // 將打印的內容添加進新的窗口
newWin.document.close() // 在IE瀏覽器中使用必須添加這一句
newWin.focus() // 在IE瀏覽器中使用必須添加這一句
setTimeout(function() {
newWin.print() // 打印
newWin.close() // 關閉窗口
}, 100)
}
以上就可以打印上面死數據的內容蝶俱,但是怎么可能只打印寫好的數據。
<div id="qrCode" ref='printModel' class="modelPrint">
<div v-for="(item,index) in printData" :key='index' style="width: 450px;page-break-after:always;">
<div style="width: 450px;padding: 0px 20px;margin-top:12px;">
<div style="text-align: center;font-weight: 700;">產品合格證名稱</div>
<div style="display: flex;align-items: center; padding-left: 15px;">
<div style="text-align: center;">
<div style="margin-left: 15px;font-size: 14px;padding-right: 4px;">
<p style="margin-bottom:0px;margin-top:7px;">產品名稱: {{item.name}}</p>
<p style="margin-bottom: 2px;margin-top:7px;">生產批次: {{item.batch}}</p>
<p style="margin-bottom: 2px;margin-top:7px;">檢驗方式: {{item.quality}}</p>
<p style="margin-bottom: 2px;margin-top:7px;">開證日期: {{item.licenceDate}}</p>
</div>
</div>
</div>
<div style="text-align: center; font-weight: 700;margin-top: 3px;">[生產經營主體對追溯信息真實性負責]</div>
</div>
</div>
</div>
methods方法
print(){
var newWin = window.open("") // 新打開一個空窗口
// this.imageToPrint = document.getElementById('qrCode') 將要被打印的內容寫靜態(tài)的時候這樣獲取是可以的饥漫,動態(tài)就獲取不到了榨呆,要換一張獲取方式
this.imageToPrint = this.$refs.printModel //用這個方式來獲取
newWin.document.write(this.imageToPrint.outerHTML) // 將打印的內容添加進新的窗口
newWin.document.close() // 在IE瀏覽器中使用必須添加這一句
newWin.focus() // 在IE瀏覽器中使用必須添加這一句
setTimeout(function() {
newWin.print() // 打印
newWin.close() // 關閉窗口
}, 100)
}
print()這個是請求后端數據之后的打印方法,我這里沒有寫獲取打印數據的接口庸队。
這里樣式說一下积蜻,我是寫的行內。也可以是其他方法彻消,但是直接在頁面正常寫class浅侨,在打印頁面是無效的。