Vue页面打印,解决退出页面失效的问题

VUE页面打印

在使用vue开发的时候,涉及到页面的打印功能,页面的按钮可能需要多次打印,可能取消之后重新操作,在使用对 document.body.innerHTML 重新赋值的方法可能导致打印之后需要重新刷新页面,很不安逸,对其重新改造了下

打印的代码

/**
 * 打印页面数据
 * @param {String} content 
 * @param {*} w 
 * @param {*} h 
 */
export function print(content, w = null, h = null) {
    // Fixes dual-screen position                         Most browsers      Firefox
    const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;
    const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;

    const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
    const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
    w = +w === 0 ? width : w;
    h = +h === 0 ? height : h;
    const left = ((width / 2) - (w / 2)) + dualScreenLeft;
    const top = ((height / 2) - (h / 2)) + dualScreenTop;
    var myWindow = window.open("", "打印", "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=" + w + ", height=" + h + ", top=" + top + ", left=" + left);
    var style = "";
    myWindow.document.write(content + style);
    myWindow.focus();
    myWindow.document.close();     //关闭document的输出流, 显示选定的数据
    myWindow.print();   //打印当前窗口
    return myWindow;
}

这里是把内容放到一个新的windows窗口中,这样使用打印就不会影响,本来的页面了

使用方式

把使用的一些代码,页都贴出来,都很简单

import { print } from 'xxxx';

doPrint () {
    var windows = print(document.getElementById('printf').innerHTML);
    windows.close();
 },
<el-row id="printf" v-show="false">
    <table class="gridtable">
         <tr>
             <th>员工姓名th><th>性别th><th>年龄th><th>工龄th>
             <th>薪资th><th>银行卡号th><th>开户行th><th width="60px">签字th>
         tr>
         <tr v-for="v in tableData">
             <td>{{v.xxx}}td>
             <td>{{v.xx}}td>
             <td>{{v.xxx}}td>
             <td>{{v.xxx}}td>
             <td>{{v.xxx}}td>
             <td>{{v.xxx}}td>
             <td>{{v.xxx}}td>
             <td>td>
         tr>
     table>
 el-row>

你可能感兴趣的:(前端开发,vue)