当前位置:首页 > 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组件结构 新建一个WeiboPost.vue组件,包含文本框、图片上传和发布按钮: <template> <div class="we…

vue实现效果

vue实现效果

以下是Vue实现常见效果的几种典型方法,分为不同场景说明: 数据绑定与响应式更新 使用v-model实现表单双向绑定: <template> <input v-model="…

vue实现RTMP

vue实现RTMP

Vue 中实现 RTMP 流播放 RTMP(Real-Time Messaging Protocol)是一种用于实时音视频流传输的协议。在 Vue 中实现 RTMP 播放通常需要借助第三方库或播放器。…

vue前端实现

vue前端实现

Vue 前端实现基础步骤 安装 Vue.js 和相关依赖 通过 npm 或 yarn 安装 Vue.js,建议使用 Vue CLI 快速搭建项目。运行命令 npm install -g @vue/cl…

vue实现监控

vue实现监控

Vue 实现监控功能的方法 在 Vue 中实现监控功能通常涉及数据变化监听、事件监听或第三方监控工具集成。以下是几种常见实现方式: 使用 Vue 的 watch 监听数据变化 通过 watch 可以…

vue实现列表循环

vue实现列表循环

Vue 列表循环的实现方法 在 Vue 中,可以通过 v-for 指令实现列表循环渲染。以下是几种常见的实现方式: 基础列表渲染 <template> <ul>…