js打印和vue打印

目录

1. js打印

2. Vue实现打印


1. js打印

  • 原生js,顶级对象window有一个print方法,可以实现打印
<div class="box">
        123
    </div>
    <button class="btn">打印</button>
    <script>
        const box = document.querySelector('.box')
        const btn = document.querySelector('.btn')
        btn.addEventListener('click', function () {
            window.document.body.innerHTML = window.document.querySelector('.box').innerHTML
            // window.document.body.style.backgroundColor = '#fff'
            window.print()
            window.location.reload()
        })
    </script>

2. Vue实现打印

  • 借助vue-print-nb插件,使用v-print指令

首先下载vue-print-nb插件

npm install vue-print-nb --save
或  yarn add vue-print-nb

然后在mian.js中引入并全局挂载

import Vue from 'vue'
import App from './App.vue'
// 引入vue-print-nb
import print from 'vue-print-nb'

Vue.config.productionTip = false

Vue.use(print) // 注册

new Vue({
  render: (h) => h(App),
}).$mount('#app')

就可以进行使用了

<template>
  <div id="app">
    123
    <el-button v-print="printObj">打印</el-button>
  </div>
</template>

<script>
export default {
  name: 'app',
  data() {
    return {
      // 打印对象
      printObj: {
        id: 'app', // 指定区域,需要打印的区域只需要加个id,并且id值为app即可
        popTitle: '标题', // 指定标题
      },
    }
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/qq_52845451/article/details/128050520