准备print.js文件
// 打印类属性、方法定义
/* eslint-disable */
export const Print = function(dom, options) ,
options
);
if (typeof dom === "string") {
this.dom = document.querySelector(dom);
} else {
this.isDOM(dom);
this.dom = this.isDOM(dom) ? dom : dom.$el;
}
this.init();
};
Print.prototype = ,
extend: function(obj, obj2) {
for (var k in obj2) {
obj[k] = obj2[k];
}
return obj;
},
getStyle: function() {
var str = "",
styles = document.querySelectorAll("style,link");
for (var i = 0; i < styles.length; i++) {
str += styles[i].outerHTML;
}
str +=
"<style>" +
(this.options.noPrint ? this.options.noPrint : ".no-print") +
"{}</style>";
return str;
},
getHtml: function() else {
inputs[k].removeAttribute("checked");
}
} else if (inputs[k].type == "text") else
}
for (var k2 = 0; k2 < textareas.length; k2++)
}
for (var k3 = 0; k3 < selects.length; k3++) else {
child[i].removeAttribute("selected");
}
}
}
}
}
// 包裹要打印的元素
// fix: https://github.com/xyl66/vuePlugs_printjs/issues/36
let outerHTML = this.wrapperRefDom(this.dom).outerHTML;
return outerHTML;
},
// 向父级元素循环,包裹当前需要打印的元素
// 防止根级别开头的 css 选择器不生效
wrapperRefDom: function(refDom) else {
prevDom = currDom.cloneNode(true);
}
currDom = currDom.parentElement;
}
return prevDom;
},
writeIframe: function(content) , 100);
};
},
toPrint: function(frameWindow)
} catch (e) {
frameWindow.print();
}
frameWindow.close();
}, 10);
} catch (err) {
console.log("err", err);
}
},
// 检查一个元素是否是 body 元素的后代元素且非 body 元素本身
isInBody: function(node) {
return node === document.body ? false : document.body.contains(node);
},
isDOM:
typeof HTMLElement === "object"
? function(obj) {
return obj instanceof HTMLElement;
}
: function(obj) {
return (
obj &&
typeof obj === "object" &&
obj.nodeType === 1 &&
typeof obj.nodeName === "string"
);
}
};
步骤二:
在需要使用的vue页面引入print.js
import { Print } from "@/assets/js/print.js";
使用实例:
<el-button class="ml-2x" @click="printPage('printTable')">打印</el-button>
<div ref="printTable">这是需要打印的内容</div>
// 打印A4纸 方法调用
printPage(val) {
Print(this.$refs[val]);
},