open-wc/context-protocol · 文件 下载 ZIP
文件最后提交记录最后更新时间
README.md
以下内容由 AI 翻译,如有问题请点此提交 issue 反馈
@open-wc/context-protocol
一个兼容 Lit 的 context-protocol community protocol] 实现方案。
安装
npm install --save @open-wc/context-protocol
使用方式
实现了 ProviderMixin 的组件将成为数据的 Provider,而实现了 ConsumerMixin 的组件则将成为数据的 Consumer。
import { ProviderMixin } from "@open-wc/context-protocol";
export class ProviderElement extends ProviderMixin(HTMLElement) {
// Set any data contexts here.
contexts = {
"number-of-unread-messages": () => {
return 0;
},
};
async connectedCallback() {
// It's also possible to provide context at any point using `updateContext`.
const response = await fetch("/api/messages/");
const data = await response.json();
this.updateContext("number-of-unread-messages", data.unreadCount);
}
}
import { ConsumerMixin } from "@open-wc/context-protocol";
export class ConsumerElement extends ConsumerMixin(HTMLElement) {
contexts = {
// Fetch contexts that we care about and subscribe to any changes.
"number-of-unread-messages": (count: number) => {
this.textContent = `${count} unread messages!`;
},
};
connectedCallback() {
// It's also possible to get any context on demand without subscribing.
this.textContent = this.getContext("number-of-unread-messages");
}
}