如何在不丢失样式的情况下打印 vue 组件的一部分 [英] How to print a part of a vue component without losing the style
本文介绍了如何在不丢失样式的情况下打印 vue 组件的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从 vue 组件打印一些内容.例如,从以下代码段中,我想打印 v-card-text
元素,该元素的 ID 也为 #print
:
new Vue({el: '#app',数据() {返回 {对话:假}},方法: {打印() {var prtContent = document.getElementById("print");var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');WinPrint.document.write(prtContent.innerHTML);WinPrint.document.close();WinPrint.focus();WinPrint.print();WinPrint.close();}}})
<头><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/vuetify/1.2.0/vuetify.min.css"/>头部><身体><div id="应用程序"><v-app id="inspire"><v-layout row justify-center><v-dialog v-model="dialog"persistent max-width="290"><v-btn slot="activator" color="primary" dark>打开对话框</v-btn><v-card><v-card-title class="headline">打印:</v-card-title><v-card-text id="print">Lorem ipsum dolor sat amet.</v-card-text><v-card-actions><v-间隔></v-间隔><v-btn color="green darken-1" flat @click.native="print">打印</v-btn></v-card></v-对话框></v-layout></v-app>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/vuetify/1.2.0/vuetify.min.js"></script></html>
但是,当我收到打印提示时,所有与之相关的样式都消失了.如何以这种方式打印 vue 组件,以便组件不会丢失关联的样式?我建议将代码片段复制到您的本地机器以获得最佳效果.
解决方案
您需要从原始文档中复制样式.尝试这样的事情:
//获取要从元素打印的 HTMLconst prtHtml = document.getElementById('print').innerHTML;//获取所有样式表 HTML让stylesHtml = '';for (const node of [...document.querySelectorAll('link[rel="stylesheet"], style')]) {styleHtml += node.outerHTML;}//打开打印窗口const WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');WinPrint.document.write(`<!DOCTYPE html><头>${stylesHtml}头部><身体>${prtHtml}