Stenciljs @Method 不工作

Stenciljs @Method not working

我正在努力让 @Method 在 stenciljs 中工作 - 任何帮助将不胜感激。

这是我的组件代码,其中包含一个名为 setName 的函数,我想在我的组件上公开它:

import { Component, Prop, Method, State } from "@stencil/core";

@Component({
  tag: "my-name",
  shadow: true
})
export class MyComponent {

  @Prop() first: string;
  @Prop() last: string;
  @State() dummy: string;

  @Method() setName(first: string, last: string): void {
    this.first = first;
    this.last = last;
    this.dummy = first + last;
  }
  render(): JSX.Element {
    return (
      <div>
        Hello, World! I'm {this.first} {this.last}
      </div>
    );
  }
}

这是引用该组件的 html 和脚本:

<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0">
  <title>Stencil Component Starter</title>
  <script src="/build/mycomponent.js"></script>

</head>
<body>

  <my-name  />

  <script>
    var myName = document.querySelector("my-name");
    myName.setName('Bob', 'Smith');
  </script>
</body>
</html>

这是我遇到的错误的屏幕截图,它是 Uncaught TypeError: myName.setName is not a function :

组件上的方法不是立即可用的;它们必须由 Stencil loaded/hydrated 才能使用。

组件有一个 componentOnReady 函数,可以在组件准备好使用时解析。所以像:

var myName = document.querySelector("my-name");
myName.componentOnReady().then(() => {
  myName.setName('Bob', 'Smith');
});

这里你不应该使用 @Method ,这不是最佳实践。我们应该始终尽量减少@Method 的使用。这有助于我们轻松扩展应用程序。

改为通过@Prop 和@Watch 传递数据。

好的,对于你的情况,请在方法名称前添加 async

只是发布另一个答案,因为这已经改变了,有了 Stencil One。

所有 @Method 修饰的方法现在在组件上立即可用,但它们必须是 async,以便您可以立即调用它们(一旦组件准备就绪它们就会解析) . componentOnReady 的使用现已过时。

但是,您应该使用自定义元素注册表的 whenDefined 方法确保该组件已在自定义元素注册表中定义。

<script>
(async () => {
  await customElements.whenDefined('my-name');

  // the component is registered now, so its methods are immediately available
  const myComp = document.querySelector('my-name');

  if (myComp) {
    await myComp.setName('Bob', 'Smith');
  }
})();
</script>