<template>
<div>
<ul class="print-ul">
<li v-for="(item,index) of tableData" :key="index"
:id="'printDiv' + index" style="page-break-after:always;">
<div>
<p>{{item.date}}</p>
<p>{{item.name}}</p>
<p>{{item.province}}</p>
<p>{{item.city}}</p>
<p>{{item.address}}</p>
<p>{{item.zip}}</p>
</div>
</li>
</ul>
<div @click="handlePrint">打印</div>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [{
date: '2016-05-03',
name: '王小虎',
province: '上海',
city: '普陀区',
address: '上海市普陀区金沙江路 1518 弄',
zip: 200333
}, {
date: '2016-05-02',
name: '王小虎',
province: '上海',
city: '普陀区',
address: '上海市普陀区金沙江路 1518 弄',
zip: 200333
}, {
date: '2016-05-04',
name: '王小虎',
province: '上海',
city: '普陀区',
address: '上海市普陀区金沙江路 1518 弄',
zip: 200333
}, {
date: '2016-05-01',
name: '王小虎',
province: '上海',
city: '普陀区',
address: '上海市普陀区金沙江路 1518 弄',
zip: 200333
}, {
date: '2016-05-08',
name: '王小虎',
province: '上海',
city: '普陀区',
address: '上海市普陀区金沙江路 1518 弄',
zip: 200333
}, {
date: '2016-05-06',
name: '王小虎',
province: '上海',
city: '普陀区',
address: '上海市普陀区金沙江路 1518 弄',
zip: 200333
}, {
date: '2016-05-07',
name: '王小虎',
province: '上海',
city: '普陀区',
address: '上海市普陀区金沙江路 1518 弄',
zip: 200333
}]
}
},
methods: {
// 调用浏览器打印
prints() {
const promiseAll = [];
const img = [];
const newWin = window.open('');
for (let i = 0; i < this.tableData.length; i++) {
const imageToPrint = document.getElementById('printDiv' + i);
imageToPrint.onload = function () {
return false;
};
newWin.document.write(imageToPrint.outerHTML);
promiseAll[i] = new Promise((resolve, reject) => {
img[i] = new Image();
img[i].src = this.tableData[i];
img[i].onload = function () {
// 第i张加载完成
resolve(img[i]);
};
img[i].onerror = function () {
reject(img[i]);
};
});
};
const styleSheet = `<style>li{list-style:none;display: flex;align-content:
center;justify-content: space-around;}</style>`;
// bca-disable-line
newWin.document.head.innerHTML = styleSheet;
newWin.document.close();
newWin.focus();
// 判断全部图片是否加载成功
Promise.all(promiseAll).then(img => {
newWin.print();
newWin.close();
}).catch(err => {
newWin.close();
this.$Message.error('图片加载失败');
});
},
}
}
</script>
<style>
.print-ul {
display: none;
width: 100%;
list-style: none;
border: 1px solid #e8e8e8;
}
</style>
注意:
⚠️如果tableData中没有image资源的话吧以下注销掉,否则会报图片加载失败。。。
promiseAll[i] = new Promise((resolve, reject) => {
img[i] = new Image();
img[i].src = this.tableData[i];
img[i].onload = function () {
// 第i张加载完成
resolve(img[i]);
};
img[i].onerror = function () {
reject(img[i]);
};
});