首页 > 解决方案 > 如何在 Vue-html-to-paper 中隐藏元素?

问题描述

当我打印页面时,我需要隐藏一些东西。当我想打印时,不想显示 2 个按钮标志。我使用插件https://www.npmjs.com/package/vue-html-to-paper

检查我的代码:

<div id="printThis">
 <h1> My tiyle </h1>
 <button> I WAN'T TO DISPLAY THIS BUTTON IN PRINT!!! </button>
 <p> My parag </p>
</div>


print(){
  this.$htmlToPaper('printThis');
}

问题很简单。我不想在我的 pdf 论文中显示按钮。

标签: javascriptvue.jsplugins

解决方案


我已经阅读了https://github.com/mycurelabs/vue-html-to-paper/blob/master/src/index.js上的源代码,看起来没有内置变量这个(真的应该有,也许你可以提出一个拉取请求?)。但是我们可以自己制作一个。

data组件的部分中,添加一个名为 的变量printing

  data() {
    return {
      printing: false,
    }
  },

编辑您的模板以使用它:

<template>
<div id="printThis">
 <h1> My tiyle </h1>
 <button v-show="!printing"> I WAN'T TO DISPLAY THIS BUTTON IN PRINT!!! </button>
 <p> My parag </p>
</div>
</template>

(请注意,您也可以使用 v-if。有一些优点和一些缺点。)

然后将插件的方法调用包装在您自己的方法中以设置和取消设置变量。使用插件文档描述的回调来取消设置变量:

print(){
  this.printing = true;
  const options = null; // Set this if you need to, based on https://randomcodetips.com/vue-html-to-paper/
  this.$htmlToPaper('printThis', options, () => {
    this.printing = false;
  });
}

你去吧。

我会说,您可能可以编写一个更好的插件来做同样的事情。最好有一个基于承诺的方法,或者至少有一些为打印成功或失败定义的生命周期事件。


推荐阅读