vue中实现打印功能【vue-easy-print】

2,343 阅读1分钟

核心用法

使用vue组件的slot插槽进行模板加载。 使用iframe复制打印区域

实现原理

需要把打印内容放到slot插槽里,vue-easy-print通过 innerHTML属性拿到需要打印内容,赋值给iframe ,通过iframe 打印功能进行打印,不是使用window.print()

快速使用

第一步 安装依赖包

 npm install vue-easy-print

第二步 在使用vue 文件里引入

import vueEasyPrint from "vue-easy-print";

export default {
    components: {vueEasyPrint}
   }

第三步 完整代码基础用法

<template>
    <div id="app">
        <button @click="printDemo">测试打印</button>
        <vue-easy-print tableShow ref="easyPrint" >
            <!-- 你自己编写打印的模板 -->
           <div>
              <p class="perpage">我的打印内容1</p>
              <p class="perpage">我的打印内容2</p>
              <p class="perpage">我的打印内容3</p>
           </div>
        </vue-easy-print>
    </div>
</template>

<script>
import vueEasyPrint from "vue-easy-print";
import demo from "./components/demo";
export default {
      data(){
         return{
         tableData:[]
         }
       },
       
       methods:{
           printDemo(){
               this.$refs.easyPrint.print();
          }
    },

}

</script>
// 也可以利用样式实现分页效果
<style lang="scss" scoped>
.perpage {
    page-break-after: always;
    padding-top: 20px;
}
</style>


详细参数

参数说明类型默认值
tableShow是否显示表格Booleanfalse
tableData针对分页表格模式:传入的打印数据Objectundefined
spaceRow针对分页表格模式:末尾空白行插入Booleanfalse
onePageRow每页多少行Number5
beforeCopy复制打印页面前调用的钩子Function
beforePrint打印页面前调用的钩子Function

vue-easy-print 官方文档

监听打印后事件案例