如何在模式Vue中使用窗口打印?

时间:2018-09-11 14:26:48

标签: javascript vue.js vuejs2 bootstrap-modal vue-component

我的Vue组件是这样的:

<template>
    ...
    <b-modal id="modalInvoice" size="lg"  title="Invoice">
        <Invoice/>
        <div slot="modal-footer" class="w-100"> 
            <b-btn size="sm" class="float-right" variant="warning" @click="show=false">
                <i class="fa fa-print"></i> Print
            </b-btn>
        </div>
    </b-modal>

    ...
        <b-btn variant="warning" class="btn-square mt-2" v-b-modal.modalInvoice @click="checkout()"><i class="fa fa-credit-card-alt"></i>Checkout</b-btn>
    ...
</template>
<script>
    ...
    export default {
        ...
        methods: {
            print() {
                window.print()
            }
        }
    }
</script>

如果单击“打印”按钮,它将起作用。但是它将显示整个网站。我只想要单击打印按钮,它仅显示模式的内容

我该怎么办?

1 个答案:

答案 0 :(得分:4)

执行此操作的一种方法是创建模式的副本,并使用CSS限制打印内容的可见性:

print () {
  const modal = document.getElementById("modalInvoice")
  const cloned = modal.cloneNode(true)
  let section = document.getElementById("print")

  if (!section) {
     section  = document.createElement("div")
     section.id = "print"
     document.body.appendChild(section)
  }

  section.innerHTML = "";
  section.appendChild(cloned);
  window.print();
}

@media screen {
  #print {
    display: none;
   }
}

@media print {
 body * {
  visibility:hidden;
  }
  #print, #print * {
    visibility:visible;
  }
  #print {
    position:absolute;
    left:0;
    top:0;
  }
}