Stenciljs @Method不起作用

8

我在stenciljs中使用@Method时遇到了困难 - 希望能得到帮助。

这是我的组件代码,其中有一个名为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”: enter image description here
3个回答

13

在组件上,方法不会立即可用;它们需要在Stencil加载/注入之后才能使用。

组件具有一个componentOnReady函数,当组件准备好使用时将被解析。因此可以这样做:

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

1
很遗憾,这个不起作用。我收到了“未捕获的TypeError:myName.componentOnReady不是函数”的错误。 - Carl Rippon
3
更正 - 更新到Stencil 0.8.2版本后,这个问题得到解决! - Carl Rippon
@CarlRippon 这就是为什么升级到Stencil后它有效的原因 https://github.com/ionic-team/stencil/blob/master/BREAKING_CHANGES.md - Lalit Kushwah
这是在StencilJs中调用方法的当前方式:(async () => { await customElements.whenDefined('todo-list'); const todoListElement = document.querySelector('todo-list'); await todoListElement.showPrompt(); })(); - Jubish Kammily
我有Stencil 2.7.0,但仍无法正常工作,这太痛苦了。 - LEMUEL ADANE

11

因为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>

0

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

相反,请通过 @Prop 和 @Watch 传递数据。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接