当前位置:首页 > VUE

vue实现局部打印

2026-01-20 23:32:56VUE

使用vue-print-nb插件实现局部打印

安装vue-print-nb插件

npm install vue-print-nb --save

在main.js中引入并注册插件

import Print from 'vue-print-nb'
Vue.use(Print)

在组件中使用v-print指令

<template>
  <div id="printArea">
    <!-- 需要打印的内容 -->
  </div>
  <button v-print="printObj">打印</button>
</template>

<script>
export default {
  data() {
    return {
      printObj: {
        id: 'printArea',
        popTitle: '打印标题' // 打印时显示的标题
      }
    }
  }
}
</script>

使用window.print()方法实现局部打印

创建打印样式

<style>
@media print {
  body * {
    visibility: hidden;
  }
  #printArea, #printArea * {
    visibility: visible;
  }
  #printArea {
    position: absolute;
    left: 0;
    top: 0;
  }
}
</style>

添加打印按钮和打印区域

<template>
  <div id="printArea">
    <!-- 需要打印的内容 -->
  </div>
  <button @click="printContent">打印</button>
</template>

<script>
export default {
  methods: {
    printContent() {
      window.print()
    }
  }
}
</script>

使用iframe实现局部打印

创建打印方法

printByIframe(content) {
  const iframe = document.createElement('iframe')
  iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;')
  document.body.appendChild(iframe)

  const doc = iframe.contentWindow.document
  doc.write(content)
  doc.close()

  iframe.contentWindow.focus()
  iframe.contentWindow.print()

  setTimeout(() => {
    document.body.removeChild(iframe)
  }, 100)
}

在组件中使用

<template>
  <div ref="printContent">
    <!-- 需要打印的内容 -->
  </div>
  <button @click="handlePrint">打印</button>
</template>

<script>
export default {
  methods: {
    handlePrint() {
      const content = this.$refs.printContent.innerHTML
      this.printByIframe(content)
    }
  }
}
</script>

使用CSS媒体查询优化打印效果

添加专门的打印样式

@media print {
  @page {
    size: A4;
    margin: 0;
  }

  body {
    padding: 1cm;
    font-size: 12pt;
    line-height: 1.5;
  }

  .no-print {
    display: none !important;
  }

  .page-break {
    page-break-after: always;
  }
}

注意事项

打印内容中避免使用背景色和背景图片,大多数浏览器默认不打印背景

对于表格等需要分页的内容,使用CSS控制分页

table {
  page-break-inside: avoid;
}

打印前可以添加loading状态,避免内容未完全渲染就开始打印

vue实现局部打印

对于动态内容,确保数据加载完成后再触发打印操作

标签: 局部vue
分享给朋友:

相关文章

vue实现triger

vue实现triger

在Vue中实现触发器(trigger)功能通常涉及自定义事件或DOM事件触发。以下是几种常见场景的实现方法: 自定义事件触发 通过$emit方法触发父组件中监听的自定义事件: // 子组件 thi…

vue tab实现

vue tab实现

Vue Tab 实现方法 使用动态组件实现 Tab 在 Vue 中可以通过动态组件 <component :is="currentTab"> 结合 v-for 和 v-bind 实现 Ta…

vue 实现遮罩

vue 实现遮罩

Vue 实现遮罩层的方法 使用固定定位和透明背景 在Vue中实现遮罩层可以通过CSS固定定位结合透明背景色完成。创建一个全屏遮罩组件,利用position: fixed覆盖整个视窗。 <tem…

vue toast实现

vue toast实现

Vue Toast 实现方法 使用第三方库(推荐) 安装 vue-toastification 库,这是一个功能丰富且轻量级的 Vue Toast 插件。 npm install vue-toast…

vue实现keepalive

vue实现keepalive

Vue 中实现 keep-alive 在 Vue 中,keep-alive 是一个内置组件,用于缓存动态组件或组件的状态,避免重复渲染和销毁。以下是实现 keep-alive 的几种方法: 基本用法…

vue实现webshell

vue实现webshell

Vue 实现 WebShell 使用 Vue 实现 WebShell 需要结合前端与后端的交互,通常通过 WebSocket 或 HTTP 协议与服务器通信。以下是一个基于 Vue 和 WebSock…