在 Vue 中,可以通过自定义打印模板来设置打印页面的样式和内容。以下是一种常用的方法:

  1. 创建一个打印模板组件,例如 PrintTemplate.vue
<template>
  <div class="print-template">
    <!-- 打印内容 -->
    <slot></slot>
  </div>
</template>

<style scoped>
.print-template {
  /* 打印页面样式 */
}
</style>
  1. 在需要打印的组件中,引入并使用打印模板组件。
<template>
  <div>
    <!-- 页面内容 -->
    <div class="page-content">
      <!-- 页面内容 -->
    </div>

    <!-- 打印按钮 -->
    <button @click="print">打印</button>

    <!-- 打印模板 -->
    <print-template ref="printTemplate">
      <!-- 打印内容 -->
      <div class="print-content">
        <!-- 打印内容 -->
      </div>
    </print-template>
  </div>
</template>

<script>
import PrintTemplate from "./PrintTemplate.vue";

export default {
  components: {
    PrintTemplate,
  },
  methods: {
    print() {
      // 获取打印模板组件实例
      const printTemplate = this.$refs.printTemplate;

      // 打印内容
      const printContent = printTemplate.$el.innerHTML;

      // 创建一个新的窗口
      const win = window.open("", "_blank");

      // 在新窗口中写入打印内容
      win.document.write(`
        <html>
          <head>
            <!-- 引入打印页面所需的样式文件 -->
          </head>
          <body>
            ${printContent}
          </body>
        </html>
      `);

      // 打印
      win.print();

      // 关闭新窗口
      win.close();
    },
  },
};
</script>

在上述代码中,我们创建了一个 PrintTemplate 组件作为打印页面的模板,其中的 <slot></slot> 标签用于插入打印内容。在需要打印的组件中,我们通过 ref 属性引用了 PrintTemplate 组件,并在打印按钮的点击事件中获取了打印内容,并将其写入新窗口中进行打印。

请注意替换注释部分的代码,以适应你的实际需求,例如引入打印页面所需的样式文件等。

同时,我们还可以使用 CSS 的 @media print 媒体查询来设置打印页面的样式。例如,可以在打印模板组件的样式中添加以下代码:

@media print {
  /* 打印页面样式 */
}

这样,当打印页面时,将应用 @media print 媒体查询中的样式

VUE 自定义打印模板设置

原文地址: http://www.cveoy.top/t/topic/hSyH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录