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

使用createApp和mount时Vue自定义元素Props传递失败求助

问题解决方案

问题根源:当你用createApp把Vue应用挂载到包含自定义元素的#my-root节点后,Vue会默认把该节点下的所有元素当作Vue模板组件解析,干扰了原生Web Component的属性传递机制,导致自定义元素接收不到prop1。

解决办法:标记原生自定义元素

在createApp之后添加配置,让Vue跳过对指定自定义元素的模板解析,保留原生属性传递逻辑:

修改main.ts代码如下:

import ...<lots of imports>
import AppCe from "./AppWebComponent.ce.vue";
import { createPinia } from "pinia";

const pinia = createPinia();
const app = createApp(App);

// 关键配置:告诉Vue my-开头的元素是原生自定义元素,不要解析为Vue组件
app.config.compilerOptions.isCustomElement = tag => tag.startsWith('my-');

app.use(pinia).use(ConfirmDialog);
app.component(...<lots of components>);
app.mount("#my-root");

const ceApp = defineCustomElement(AppCe);
customElements.define("my-element", ceApp);

额外注意点

你当前代码存在类型不匹配问题:自定义元素的prop1定义为number类型,但index.html里传递的是字符串"abc"。Web Components的属性默认是字符串类型,若需要传递数字,可在组件内部将字符串转为数字,或通过原生JS直接赋值(如document.querySelector('my-element').prop1 = 123);如果是在Vue模板中使用自定义元素,也可以用:prop1.number="123"的方式绑定数字类型值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:30:56