vue3使用vue3-print-nb打印

在 Vue 3 中使用 vue3-print-nb 实现打印功能,请按以下步骤操作:


1. 安装依赖

bash 复制代码
npm install vue3-print-nb
# 或
yarn add vue3-print-nb

2. 全局注册插件

main.js 中引入并注册:

javascript 复制代码
import { createApp } from 'vue';
import App from './App.vue';
import Print from 'vue3-print-nb';

const app = createApp(App);
app.use(Print);
app.mount('#app');

3. 在组件中使用

通过指令 v-print 绑定打印区域:

vue 复制代码
<template>
  <div>
    <!-- 打印按钮 -->
    <button v-print="printOptions">打印</button>
    
    <!-- 需要打印的内容 -->
    <div id="printContent">
      <h1>打印标题</h1>
      <p>打印内容示例...</p>
    </div>
  </div>
</template>

<script setup>
const printOptions = {
  id: 'printContent',     // 要打印的DOM元素ID
  popTitle: '打印页标题',  // 打印页的标题(可选)
  extraCss: '',           // 额外CSS样式链接(可选)
  extraHead: ''           // 额外HTML头部内容(可选)
};
</script>

4. 自定义样式

在打印内容中添加专属样式:

vue 复制代码
<style scoped>
@media print {
  #printContent {
    padding: 20mm;
    font-size: 12pt;
  }
  button {
    display: none; /* 打印时隐藏按钮 */
  }
}
</style>

5. 完整示例

vue 复制代码
<template>
  <div>
    <button v-print="printConfig">打印当前页</button>
    <div id="printArea">
      <h2>订单详情</h2>
      <table>
        <tr><th>项目</th><th>金额</th></tr>
        <tr><td>商品A</td><td>¥100</td></tr>
        <tr><td>运费</td><td>¥10</td></tr>
      </table>
    </div>
  </div>
</template>

<script setup>
const printConfig = {
  id: 'printArea',
  popTitle: '订单_' + new Date().toLocaleDateString()
};
</script>

<style>
@media print {
  #printArea table {
    width: 100%;
    border-collapse: collapse;
  }
  #printArea th, #printArea td {
    border: 1px solid #000;
    padding: 8px;
  }
}
</style>

⚠️ 注意事项

  1. 浏览器兼容性:依赖浏览器原生打印功能,不同浏览器效果可能有差异
  2. 样式隔离 :通过 @media print 定义打印专用样式
  3. 动态内容 :确保打印前数据已完成渲染(可配合 nextTick 使用)
相关推荐
小徐_233321 分钟前
Wot UI 2.2.0 发布:Button 新增 subtle,VideoPreview 预览体验继续增强
前端·微信小程序·uni-app
山河木马2 小时前
矩阵专题3-怎么创建投影矩阵(uProjectionMatrix)
javascript·webgl·计算机图形学
天蓝色的鱼鱼3 小时前
关于 CSS 你可能不知道的属性,但关键时刻很有用
前端·css
泯泷3 小时前
第 2 篇:设计第一套字节码:Opcode、Instruction 与 Constant Pool
前端·javascript·安全
妙码生花3 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十五):优化细节、网络请求封装
前端·后端·ai编程
泯泷3 小时前
第 1 篇:从 1 + 2 开始:亲手写出第一台 JSVM
前端·javascript·安全
团团崽_七分甜3 小时前
Spring Boot 核心知识点总结
前端
lichenyang4534 小时前
从一个按钮开始,理解 ASCF 框架到底在做什么
前端
古夕4 小时前
第三方 SSO 接入实践:redirect_uri 编码、回调一致性与跨项目联调
前端·vue.js