You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Vue子组件仅在父组件完全挂载后渲染,解决$refs传值undefined问题

最优优化方案:调整子组件元素获取逻辑,避免挂载时机依赖

你遇到的问题本质是$refs只有在父组件完全挂载后才会完成初始化,而子组件props的读取时机早于这个节点,只需要将元素获取的时机延迟到点击导出的瞬间,就可以完全避免这个问题,不需要在每个父组件加冗余的判断逻辑。


方案1:子组件接收获取元素的函数(最推荐)

修改ExportPdf.vue代码如下:

<template>
  <div>
      <button class="px-6 py-3 rounded bg-gray-600 hover:bg-gray-900 text-white text-sm font-bold whitespace-no-wrap" 
        @click="exportToPDF">Export to PDF
    </button>
  </div>
</template>

<script>
import html2pdf from 'html2pdf.js'

export default {
props:{
    // 改为接收返回目标元素的函数,不直接接收元素实例
    getArea: {
      type: Function,
      required: true
    },
    name : String,
    orientation : {
      type: String,
      default(){
        return 'landscape'
      }
    }
},
methods:{
     exportToPDF () {
          // 点击导出时才调用函数获取最新的元素实例
          const targetArea = this.getArea()
          if (!targetArea) {
            console.warn('未找到待导出的内容区域')
            return
          }
          html2pdf(targetArea, {
            margin: [1.5, 1],
            filename: this.name + '.pdf',
            image: { type: 'jpeg', quality: 0.98 },
            html2canvas: {scale: 2},
            jsPDF: { unit: 'cm', format: 'a4', orientation: this.orientation ,  floatPrecision: 16 }
        })
    }
}
}
</script>

父组件使用时不需要加任何v-if判断和mounted额外逻辑,直接按以下方式传参即可:

<export-pdf name="Liste des consommables des équipements" :get-area="() => $refs.content" />

<div ref="content">
 <!-- 待导出的内容 -->
</div>

方案2:子组件通过选择器定位元素(更简洁)

如果不想传函数,也可以直接让子组件通过DOM选择器定位目标元素,修改ExportPdf.vue的props和获取逻辑:

props:{
    // 接收目标元素的CSS选择器
    targetSelector: {
      type: String,
      required: true
    },
    // 其他prop保持不变
},
methods:{
     exportToPDF () {
          const targetArea = document.querySelector(this.targetSelector)
          // 后续导出逻辑不变
    }
}

父组件使用时只需要给待导出区域加个id,连ref都不需要定义:

<export-pdf name="Liste des consommables des équipements" target-selector="#pdf-content" />

<div id="pdf-content">
 <!-- 待导出的内容 -->
</div>

内容的提问来源于stack exchange,提问作者Abdou_dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 17:48:03