当前位置:首页 > 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>

添加打印按钮和打印区域

vue实现局部打印

<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媒体查询优化打印效果

添加专门的打印样式

vue实现局部打印

@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实现反向推送

Vue 实现反向推送的方法 反向推送通常指子组件向父组件传递数据或触发事件。在 Vue 中,可以通过以下几种方式实现反向推送。 使用 $emit 触发自定义事件 子组件通过 $emit 方法触发一个…

vue 怎么实现tab

vue 怎么实现tab

实现 Tab 的基本方法 在 Vue 中实现 Tab 功能可以通过动态组件或条件渲染完成。以下是一个使用 v-if 和 v-for 的常见方案: <template> <div…

vue实现拖拽

vue实现拖拽

Vue 实现拖拽功能的方法 使用 HTML5 原生拖拽 API HTML5 提供了原生的拖拽 API,可以通过 draggable 属性和相关事件实现拖拽功能。在 Vue 中可以通过绑定这些事件来实现…

vue实现全选

vue实现全选

Vue 实现全选功能 全选功能通常用于表格或列表中,允许用户一键选择所有项目。以下是几种实现方式: 使用 v-model 和计算属性 在数据中维护一个数组存储选中项的 ID,通过计算属性实现全选逻辑…

vue实现验证码

vue实现验证码

Vue 实现验证码的方法 使用 Canvas 生成图形验证码 安装依赖(如需要): npm install vue-canvas-verify --save 创建验证码组件: <te…

vue的实现原理

vue的实现原理

Vue 的实现原理 Vue 是一个渐进式 JavaScript 框架,其核心实现原理主要包括响应式系统、虚拟 DOM、模板编译和组件化机制。以下是 Vue 实现原理的关键部分: 响应式系统 Vue…