作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在开展一个项目,我希望该功能能够打印我的页面的特定元素。有一个名为 VueHtmlToPaper 的 mixin/plugin 可以完全满足我的要求,但是我无法将它导入到我的 Vue 3 CLI 项目中,因为它是为 VueJS2 创建的,并且全局 API 不同。任何帮助表示赞赏。
main.js
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
项目结构:
最佳答案
由于这个插件与 vue 3 不兼容,我们可以基于 vue-html-to-paper 做我们的插件插件:
VueHtmlToPaper.js
文件:
function addStyles(win, styles) {
styles.forEach((style) => {
let link = win.document.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", style);
win.document.getElementsByTagName("head")[0].appendChild(link);
});
}
const VueHtmlToPaper = {
install(app, options = {}) {
app.config.globalProperties.$htmlToPaper = (
el,
localOptions,
cb = () => true
) => {
let defaultName = "_blank",
defaultSpecs = ["fullscreen=yes", "titlebar=yes", "scrollbars=yes"],
defaultReplace = true,
defaultStyles = [];
let {
name = defaultName,
specs = defaultSpecs,
replace = defaultReplace,
styles = defaultStyles
} = options;
// If has localOptions
// TODO: improve logic
if (!!localOptions) {
if (localOptions.name) name = localOptions.name;
if (localOptions.specs) specs = localOptions.specs;
if (localOptions.replace) replace = localOptions.replace;
if (localOptions.styles) styles = localOptions.styles;
}
specs = !!specs.length ? specs.join(",") : "";
const element = window.document.getElementById(el);
if (!element) {
alert(`Element to print #${el} not found!`);
return;
}
const url = "";
const win = window.open(url, name, specs, replace);
win.document.write(`
<html>
<head>
<title>${window.document.title}</title>
</head>
<body>
${element.innerHTML}
</body>
</html>
`);
addStyles(win, styles);
setTimeout(() => {
win.document.close();
win.focus();
win.print();
win.close();
cb();
}, 1000);
return true;
};
}
};
export default VueHtmlToPaper;
我刚刚复制/粘贴了 code我将 Vue
替换为 app
,然后将其导入 main.js
:
import { createApp } from 'vue'
import App from './App.vue'
import VueHtmlToPaper from './plugins/VueHtmlToPaper'
let app=createApp(App);
app.use(VueHtmlToPaper)
app.mount('#app')
然后在任何组件中使用它:
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png">
<!-- SOURCE -->
<div id="printMe">
<h1>Print me!</h1>
</div>
<!-- OUTPUT -->
<button @click="print">print</button>
</div>
</template>
<script lang="ts">
import {
defineComponent
} from 'vue';
import HelloWorld from '@/components/HelloWorld.vue'; /
export default defineComponent({
name: 'Home',
components: {
HelloWorld,
},
methods: {
print() {
this.$htmlToPaper('printMe')
}
},
mounted() {
}
});
</script>
关于javascript - 如何在 Vue 3 中打印特定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64824171/
我是一名优秀的程序员,十分优秀!