尝试访问DOM的clientWidth和clientHeight引用时出现Vue问题

时间:2020-11-09 16:40:53

标签: html typescript vue.js vuejs2 vue-class-components

类型'Vue |中不存在属性'clientWidth'元素| Vue [] | Element []'。
属性'clientHeight'在类型'Vue |中不存在。元素| Vue [] | Element []'。

<div class="invoice-step-detail" id="invoice" ref="invoice">

@Component({
    name: 'CreateInvoice',
    components: { }
})
export default class CreateInvoice extends Vue {

downloadPdf(){
        let pdf = new jsPDF("p", "pt", "a4", true);
        let invoice = document.getElementById('invoice');
        let width = this.$refs.invoice.clientWidth;
        let height = this.$refs.invoice.clientHeight;

        html2canvas(invoice!).then(canvas => {
            let image = canvas.toDataURL('image/png');
            pdf.addImage(image, 'PNG', 0, 0, width * 0.55, height * 0.55);
            pdf.save('invoice');
        })
    }
async submitInvoice(): Promise<void> {
        this.invoice = {
            createdOn: new Date,
            updatedOn: new Date,
            customerId: this.selectedCustomerId,
            lineItems: this.lineItems,
        };
        await invoiceService.makeNewInvoice(this.invoice);

        this.downloadPdf();
        await this.$router.push("/orders");
    }
}

有什么建议吗?我仍然是新手,很奇怪的是,此代码以这种方式工作,但引发了该错误。

1 个答案:

答案 0 :(得分:1)

在组件中添加字段$refs,其中包含您定义的引用,类型为HTMLElement

export default class CreateInvoice extends Vue {
$refs:{
  invoice:HTMLElement
}
downloadPdf(){
...

有关更多详细信息,请检查this