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

如何在SweetAlert2弹窗内容中正确使用并渲染Vue3自定义组件

你遇到的问题本质是SweetAlert2的html配置仅支持原生HTML字符串,没有接入Vue的模板编译能力,直接传入Vue组件标签字符串只会被当做普通自定义标签处理,不会渲染组件实际内容。

实现代码

直接修改触发弹窗的逻辑即可,无需修改原有TestComponent:

<script>
import { createVNode, render } from 'vue'
import Swal from "sweetalert2";
import TestComponent from "@/components/TestComponent";

export default {
  name: "OtherComponent",
  methods: {
    clickAction() {
      // 生成组件虚拟节点,第二个参数可传props、事件回调
      const testVnode = createVNode(TestComponent)
      // 创建临时挂载容器
      const mountDom = document.createElement('div')
      // 将虚拟节点渲染为真实DOM
      render(testVnode, mountDom)

      // 弹窗调用
      Swal.fire({
        html: mountDom.firstChild
      })

      // 弹窗关闭时销毁组件实例,避免内存泄漏
      Swal.getPopup().addEventListener('destroyed', () => {
        render(null, mountDom)
      })
    }
  }
};
</script>
扩展说明

如果需要给组件传递参数、绑定事件,可在createVNode的第二个参数中配置:

const testVnode = createVNode(TestComponent, {
  // 传递props
  content: '弹窗内自定义内容',
  // 绑定自定义事件
  onConfirm: () => {
    console.log('组件内触发了确认事件')
    Swal.close()
  }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:54:09