从Svelte Web组件中揭示方法
我想拥有一种从Svelte Web组件中暴露的方法,以便组件的消费者可以称呼它。
假设我在这里有一个简单的Svelte Web组件:
<script>
export function someMethod() {
console.log("I was called");
}
</script>
<svelte:options tag="svelte-div" />
<style>
div {
background: #ff3e00;
}
</style>
<div>
I am just a placeholder
</div>
一些不可知论的消费者应该能够调用该方法。可能是苗条的,可能是香草,可能是反应。像这样:
const svelteDiv = document.querySelector("svelte-div");
if (svelteDiv) svelteDiv.someMethod();
Svelte的 compileroptions:True
已设置。
上述作品完美无缺,我认为与Svelte一起也可以做到这一点。我的计算机上的构建文件还包括必要的 customElements.define
行,但我无法在DOM节点上调用此方法。我在文档中找不到任何东西。下面是上面设置的沙箱。
https://codesandbox.io/s/codesandbox.io/s/s/vigorof-euler-euler-euler-jp9ejd ?file =/app.svelte
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您尝试创建并使用同一项目的自定义元素,我认为这无法正常工作。如果添加了编译器选项
customElement:true
,bundle.js
将在public> public/build/build
使用npm run build
。该文件包含自定义元素,然后可以在另一个项目中复制,重命名和使用。如评论中所述,看起来您无法更改codesandbox中的
lollup.config
文件。此外,您还需要访问终端才能运行构建。在CodesandBox文档中,提到了两个环境 client&amp;容器环境 Svelte One似乎是没有终端的客户环境。也许一切都可以通过容器环境设置,但是我认为最好切换到本地安装的IDE,例如这是教程 Web组件。
基本上有三个步骤
&lt; svelte:options tag =“ my-custom-element”/&gt;
您要导出要导出的组件顶部code> customelement:true
to to to编译器选项lolup.config.js
main.js
,因此它仅包含要导出的组件的导入,要导出为Web组件,例如从' ./mycustomelement.svelte';
,而其他任何东西都无法在自定义元素上调用,与Svelte组件不同
You try to create and to use the custom element from the same project, which I don't think can work. If you add the compiler option
customElement: true
, abundle.js
file will be created underpublic/build
when building the project withnpm run build
. This file contains the custom elements and can then be copied, renamed and used in a different project.Like mentioned in the comments it looks like you can't change the
rollup.config
file in the codesandbox. Besides you need access to the terminal to run the build. In the codesandbox docs two environments are mentioned Client & Container Environments The Svelte one seems to be a Client environment without a terminal. Maybe everything could be set up via a Container Environment, but I assume it would be better to switch to a locally installed IDE like Visual Studio CodeHere's a tutorial going trough the process of building web components.
There are basicily three steps
<svelte:options tag="my-custom-element" />
to top of Component you want to exportcustomElement: true
to compiler options inrollup.config.js
main.js
so that it contains only imports of the components you want to export as web components likeimport MyCustomElement from './MyCustomElement.svelte';
and nothing elseThe exported function can be called on the custom element and unlike with Svelte Components