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 使用)
相关推荐
子兮曰5 小时前
async/await高级模式:async迭代器、错误边界与并发控制
前端·javascript·github
恋猫de小郭5 小时前
2026 Flutter VS React Native ,同时在 AI 时代 VS Native 开发,你没见过的版本
android·前端·flutter
GIS之路7 小时前
ArcGIS Pro 中的 Notebooks 入门
前端
IT_陈寒9 小时前
React状态管理终极对决:Redux vs Context API谁更胜一筹?
前端·人工智能·后端
lemon_yyds9 小时前
《vue 2 升级vue3 父组件 子组件 传值: value 和 v-model
vue.js
Kagol10 小时前
TinyVue 支持 Skills 啦!现在你可以让 AI 使用 TinyVue 组件搭建项目
前端·agent·ai编程
柳杉10 小时前
从零打造 AI 全球趋势监测大屏
前端·javascript·aigc
simple_lau10 小时前
Cursor配置MasterGo MCP:一键读取设计稿生成高还原度前端代码
前端·javascript·vue.js
睡不着先生10 小时前
如何设计一个真正可扩展的表单生成器?
前端·javascript·vue.js
天蓝色的鱼鱼10 小时前
模块化与组件化:90%的前端开发者都没搞懂的本质区别
前端·架构·代码规范