我在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](https://istack.dev59.com/BtD1k.webp)