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

实现 vue 框架

Vue 框架的基本实现 Vue 是一个渐进式 JavaScript 框架,用于构建用户界面。以下是实现 Vue 框架的基本步骤和核心概念。 核心概念 响应式数据绑定 Vue 的核心特性之一是响应式数…

vue实现复选

vue实现复选

Vue 实现复选框 在 Vue 中实现复选框可以通过 v-model 指令绑定数据,同时结合 input 元素的 type="checkbox" 属性来实现。以下是几种常见的实现方式: 单个复选框…

vue diff实现

vue diff实现

Vue Diff 算法实现原理 Vue 的虚拟 DOM Diff 算法(即 patch 过程)是其高效渲染的核心,主要通过对比新旧虚拟节点的差异,最小化 DOM 操作。以下是关键实现要点: 同层级比…

vue 实现后退

vue 实现后退

实现后退功能的方法 在Vue中实现后退功能通常需要结合浏览器历史记录API或Vue Router的导航方法。以下是几种常见的实现方式: 使用Vue Router的go方法 this.$router…

vue实现treeview

vue实现treeview

Vue 实现 TreeView 的方法 使用递归组件实现 TreeView 递归组件是 Vue 中实现 TreeView 的常见方式。通过组件调用自身,可以轻松处理嵌套的树形结构数据。 <te…

vue实现dag

vue实现dag

Vue实现DAG(有向无环图) 在Vue中实现DAG(Directed Acyclic Graph,有向无环图)通常涉及数据结构的建模、可视化渲染以及交互逻辑处理。以下是关键实现步骤和示例代码: 数…