当前位置:首页 > VUE

vue实现打印预览功能

2026-02-21 06:49:29VUE

使用vue-print-nb插件实现打印预览

安装vue-print-nb插件:

npm install vue-print-nb --save

在main.js中引入并注册:

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

在组件中使用:

<template>
  <div id="printContent">
    <!-- 需要打印的内容 -->
    <h1>打印测试</h1>
    <p>这是要打印的内容</p>
  </div>
  <button v-print="printObj">打印</button>
</template>

<script>
export default {
  data() {
    return {
      printObj: {
        id: 'printContent',
        popTitle: '打印标题', // 打印窗口标题
        extraCss: 'https://example.com/style.css' // 额外CSS
      }
    }
  }
}
</script>

使用window.print原生方法实现

创建打印方法:

methods: {
  handlePrint() {
    const printContent = document.getElementById('printContent').innerHTML
    const originalContent = document.body.innerHTML

    document.body.innerHTML = printContent
    window.print()
    document.body.innerHTML = originalContent
  }
}

添加打印按钮:

<template>
  <div id="printContent">
    <!-- 打印内容 -->
  </div>
  <button @click="handlePrint">打印</button>
</template>

使用CSS控制打印样式

添加打印专用样式:

@media print {
  body * {
    visibility: hidden;
  }
  #printContent, #printContent * {
    visibility: visible;
  }
  #printContent {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
  }
}

使用iframe实现打印预览

创建iframe打印方法:

printWithIframe() {
  const content = document.getElementById('printContent').innerHTML
  const iframe = document.createElement('iframe')

  document.body.appendChild(iframe)
  iframe.contentDocument.write(content)
  iframe.contentDocument.close()

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

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

注意事项

打印内容中避免使用浮动元素和绝对定位,可能导致打印布局问题

对于复杂表格,建议使用专门的打印样式表控制显示

测试不同浏览器的打印效果,Chrome和Firefox可能存在差异

vue实现打印预览功能

批量打印时考虑使用队列机制,避免打印窗口被拦截

标签: 功能vue
分享给朋友:

相关文章

vue实现中台

vue实现中台

Vue 实现中台系统的关键步骤 技术选型与基础搭建 使用 Vue 3(Composition API)或 Vue 2(Options API)作为前端框架,搭配 Vue Router 实现路由管理,V…

vue实现图集

vue实现图集

Vue 实现图集的方法 在 Vue 中实现图集功能可以通过多种方式完成,以下是一些常见的方法和实现步骤。 使用第三方库(如 vue-image-lightbox) 安装 vue-image-ligh…

vue实现bootstrap

vue实现bootstrap

Vue 中集成 Bootstrap 的方法 在 Vue 项目中集成 Bootstrap 可以通过以下方式实现,涵盖样式、组件和交互功能。 安装 Bootstrap 依赖 通过 npm 或 yarn…

vue实现截屏怎么实现

vue实现截屏怎么实现

Vue实现截屏的方法 使用html2canvas库 html2canvas是一个流行的JavaScript库,可以将网页元素转换为Canvas图像。在Vue项目中安装html2canvas: npm…

vue 实现异步加载

vue 实现异步加载

Vue 实现异步加载的方法 使用动态 import 实现组件懒加载 在 Vue 中可以通过动态 import() 语法实现组件的异步加载,这会使得组件在需要时才被加载,减少初始加载时间。 const…

vue路由实现iframe

vue路由实现iframe

在Vue中实现iframe嵌入可以通过路由配置和组件动态加载来完成。以下是具体实现方法: 路由配置 在Vue Router的路由配置中,通过component属性动态加载iframe组件。需要将目标…