メインコンテンツまでスキップ
バージョン: v5 (Preview)

メソッドデコレータ

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!

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();
})();

In this playground, the button in index.html calls showPrompt():

index.html
<script type="module" src="./todo-list.js"></script>

<button>Add a todo</button>
<todo-list></todo-list>

<script>
document.querySelector('button').addEventListener('click', async () => {
await customElements.whenDefined('todo-list');
const todoListElement = document.querySelector('todo-list');
await todoListElement.showPrompt();
});
</script>
todo-list.tsx
import { Component, Method, State } from '@stencil/core';

@Component({ tag: 'todo-list' })
export class TodoList {
@State() prompting = false;

@Method()
async showPrompt() {
this.prompting = true;
}

render() {
return this.prompting ? <input placeholder="What needs doing?" /> : <p>No prompt yet</p>;
}
}

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

ステンシルのアーキテクチャはすべてのレベルで非同期であるため、多くのパフォーマンス上の利点と使いやすさが可能になります。 @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>
);
}
}