メインコンテンツまでスキップ
バージョン: v4.36

メソッドデコレータ

The @Method() decorator is used to expose methods on the public API. Functions decorated with the @Method() decorator can be called directly from the element, i.e. they are intended to be callable from the outside!

注記

Developers should try to rely on publicly exposed methods as little as possible, and instead default to using properties and events as much as possible. As an app scales, we've found it's easier to manage and pass data through @Prop rather than public methods.

import { Method } from '@stencil/core';

export class TodoList {

@Method()
async showPrompt() {
// show a prompt
}
}

次のようなメソッドを呼び出します。

注記

Developers should ensure that the component is defined by using the whenDefined method of the custom element registry before attempting to call public methods.

(async () => {
await customElements.whenDefined('todo-list');
const todoListElement = document.querySelector('todo-list');
await todoListElement.showPrompt();
})();

パブリックメソッドは非同期である必要があります​

ステンシルのアーキテクチャはすべてのレベルで非同期であるため、多くのパフォーマンス上の利点と使いやすさが可能になります。 @Methodデコレータを使用して公開されたメソッドを確実に返すことにより、promiseが返されます。

  • 開発者は、componentOnReady()を使用せずに、実装がダウンロードされる前にメソッドを呼び出すことができます。componentOnReady()は、メソッド呼び出しをキューに入れ、コンポーネントのロードが完了した後に解決します。

  • コンポーネントとの相互作用は、遅延読み込みが必要な場合でも、すでに完全に水和されている場合でも同じです。

  • コンポーネントのパブリックAPIの非同期を維持することで、アプリはコンポーネントを透過的にWeb Workerに移動でき、APIは引き続き同じ。

  • promiseを返す必要があるのは、 @Methodデコレータを持つ公開されたメソッドの場合のみです。 他のすべてのコンポーネントメソッドはコンポーネント専用であり、非同期である必要はありません

// VALID: using async
@Method()
async myMethod() {
return 42;
}

// VALID: using Promise.resolve()
@Method()
myMethod2() {
return Promise.resolve(42);
}

// VALID: even if it returns nothing, it needs to be async
@Method()
async myMethod3() {
console.log(42);
}

// INVALID
@Method()
notOk() {
return 42;
}

プライベートメソッド​

非公開メソッドは、コンポーネントのビジネスロジックを整理するために引き続き使用でき、Promiseを返す必要はありません。

class Component {
// `getData`は@Methodで公開されているパブリックメソッドではないため
// 非同期である必要はありません
getData() {
return this.someData;
}
render() {
return (
<div>{this.getData()}</div>
);
}
}