下載print.js到本地侣监,放入靜態(tài)資源文件中撤蚊,在main.js中引入:
import Print from './util/print'
Vue.use(Print)
在需要打印的頁(yè)面直接調(diào)用就可以了
<template>
<div ref=print>
需要打印的內(nèi)容
</div>
<div @click=“print”>點(diǎn)擊打印 </div>
</template>
<script>
methods:{
pritn(){
this.$print(this.$refs.print)
}
}
</script>
這樣就可以是不是很簡(jiǎn)單
原本看他的文檔是可以篩選不打印的元素五鲫,但是試了下不行
于是我就把不打印的元素在打印的時(shí)候直接隱藏
handlePrint () {
this.showBtn = false // 隱藏因素
setTimeout(() => {
this.$print(this.$refs.print)
this.showBtn = true // 顯示元素
}, 50)
},
這樣就OK了
============================= 華麗的分割線 =================================
存在的問(wèn)題:
上述方法在打印大型文檔,會(huì)出現(xiàn)打印不全的問(wèn)題。
解決方法:
用
window.print()
自帶方法解決沪羔。先把需要打印的內(nèi)容,拷貝到一個(gè)新的窗口中象浑,然后再用window自帶的打印window.print()
來(lái)實(shí)現(xiàn)打印蔫饰。
html部分
<template>
<div>
<div id="printContent">
...
</div>
<div @click="winPrint()">打印</div>
</div>
</template>
js部分
winPrint() {
let curId,timer,timer2,newStr,wind,cssUrl,nodeEnv,new_element;
newStr = document.getElementById(curId).innerHTML;
wind = window.open(
"",
"newwindow",
"height=660, width=1000, top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=n o, status=no"
);
wind.document.body.innerHTML = newStr;
new_element = document.createElement("link");
new_element.setAttribute("rel", "stylesheet");
new_element.setAttribute("style", "text/css");
//針對(duì)開(kāi)發(fā)環(huán)境和生產(chǎn)環(huán)境分別設(shè)置css
cssUrl = "";
nodeEnv = process.env.VUE_APP_MODE;
if (nodeEnv === "development" || nodeEnv === "test") {
cssUrl = process.env.VUE_APP_MAP_URL + "/css.css";
} else if (nodeEnv === "production") {
cssUrl = "https://xxx/css.css";
}
new_element.setAttribute(
"href",
cssUrl
);
wind.document.body.appendChild(new_element);
clearTimeout(timer);
clearTimeout(timer2);
timer = setTimeout(() => {
wind.window.print();
timer2 = setTimeout(() => {
wind.window.close();
}, 0);
}, 1000);
return false;
}