1.安装依赖并引入
npm install vue3-print-nb --save
全局引入:
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')
局部引入:
import print from 'vue3-print-nb'
directives: {
print
}
2.项目中使用
打印整个页面:
<template>
<button v-print>打印</button>
</template>
打印某个区域:
<template>
<!-- <button v-print="'#printMe'">打印</button> -->
<button v-print="printObj">打印</button>
<div id="printMe">
这里是需要打印的内容
</div>
</template>
<script setup>
const printObj = {
id: 'printMe',
popTitle: '页眉标题',
extraCss: '',
extraHead: '',
beforeOpenCallback (vue) {
console.log('打开之前');
},
openCallback (vue) {
console.log('执行了打印');
},
closeCallback (vue) {
console.log('关闭了打印工具');
},
};
</script>
打印URL:
<template>
<button v-print="printObj">打印</button>
</template>
<script setup>
const printObj = {
url: 'http://localhost:8080/',
};
</script>
3.注意事项
当 html、body 标签设置 height=“100%” 时会导致打印页面多出一个空白页。
可以通过设置 extraHead 解决:
<script setup>
const printObj = {
id: 'printMe',
extraHead: `
<style>
html, body {
height: auto !important;
}
</style>
`,
};
</script>