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

在Vue页面添加多个HubSpot表单遇加载问题求助

Vue页面加载多个HubSpot表单的解决方案

问题根源

你当前的实现每次组件挂载时都会重复插入HubSpot表单脚本,重复加载脚本会导致window.hbspt实例冲突,进而只能渲染单个表单。

解决方案

核心思路是只加载一次HubSpot脚本,复用已初始化的hbspt实例创建多个表单。

代码实现

mounted() {
  // 检查页面是否已加载HubSpot表单脚本
  const existingScript = document.querySelector('script[src="https://js.hsforms.net/forms/v2.js"]');

  if (existingScript) {
    // 脚本已存在,直接创建多个表单
    this.renderHubSpotForms();
  } else {
    // 首次加载脚本
    const script = document.createElement("script");
    script.src = "https://js.hsforms.net/forms/v2.js";
    document.body.appendChild(script);
    script.addEventListener("load", () => {
      if (window.hbspt) {
        this.renderHubSpotForms();
      }
    });
  }
},
methods: {
  renderHubSpotForms() {
    // 渲染第一个表单
    window.hbspt.forms.create({
      portalId: "1791848",
      formId: "ffad341d-b632-4280-a0c7-7141007bac69",
      target: "#hubspotForm1",
    });

    // 渲染第二个表单(替换为你的实际表单ID和目标容器)
    window.hbspt.forms.create({
      portalId: "1791848",
      formId: "your-second-form-id",
      target: "#hubspotForm2",
    });

    // 更多表单按此格式添加即可
  }
}

注意事项

  • 确保页面中存在对应target属性的DOM容器,比如两个不同ID的div:<div id="hubspotForm1"></div>和<div id="hubspotForm2"></div>
  • 如果多个组件都需要渲染HubSpot表单,建议把脚本加载逻辑放到全局(如App.vue的mounted钩子),避免重复加载脚本
  • 每个表单需要使用唯一的formId和对应的target容器ID

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 05:55:17