asynceventhandlersinlit-html
创始人
2024-09-21 02:30:54
0

在 lit-html 中添加异步事件处理程序可以很方便地执行一些异步操作。但是,这也会导致一些问题,因为异步函数的返回值不会影响模板渲染。

为了解决这个问题,可以使用 lit-html 的 directive,即repeat、classMap、styleMap、live、guard等。

例如,使用 live directive可以使渲染函数等待 Promise 返回的值:

import {live} from 'lit-html/directives/live';

const handleClick = async (event) => { const result = await fetch('/data');

return result.json(); };

html ;

这里的 live directive 会使用 requestRender,在 Promise 返回结果后重新渲染值。 这种方式可以避免渲染出不正确的值。

另外,还可以使用 asyncState directive,它会等待异步函数执行完成并返回结果。

import {asyncState} from 'lit-html/directives/async-state';

const handleClick = async (event) => { const result = await fetch('/data');

return result.json(); };

html ;

在这个示例中,asyncState directive 会将 handleClick 函数返回的 Promise 转换为一个对象,其包含以下属性:‘data’(Promise 执行结果)、‘error’(如果 Promise 拒绝时返回),以及‘isLoading’(如果 Promise 还没有执行完成)。

通过在模板中使用(state) => html${state.data}``,可以将结果呈现为一个文本节点。

相关内容

热门资讯

透视透视!wepoker辅助器... 透视透视!wepoker辅助器怎么用,wepoker轻量版书签,技巧教程(原先真的是有挂)关于wep...
透视ai!德普之星透视辅助软件... 1、透视ai!德普之星透视辅助软件下载,hhpoker透视脚本,2025新版教程(本来是真的有挂);...
透视黑科技!wpk辅助ai,w... 透视黑科技!wpk辅助ai,wepoker透视底牌,靠谱教程(一向有挂);超受欢迎的wepoker透...
透视了解!德普之星透视辅助插件... 透视了解!德普之星透视辅助插件,wepoker如何设置透视,攻略方法(固有存在有挂)这是由厦门游乐互...
透视玄学!德普之星辅助器app... 透视玄学!德普之星辅助器app,we poker辅助器,微扑克教程(最初是真的有挂);亲们利用一分钟...
透视透视!wepoker透视脚... 透视透视!wepoker透视脚本下载,pokemmo辅助脚本,可靠教程(先前存在有挂)是一款可以让一...
透视辅助!hhpoker辅助下... 透视辅助!hhpoker辅助下载,wepoker透视app下载,必赢方法(原本有挂)相信很多朋友都在...
透视能赢!hhpoker万能辅... 《hhpoker万能辅助器软件透明挂》是一款多人竞技的hhpoker万能辅助器辅助透视游戏,你将微扑...
透视辅助!wpk辅助器是真的吗... 透视辅助!wpk辅助器是真的吗,fishpoker透视,透视教程(先前有挂)是一款可以让一直输的玩家...
透视透视!德普之星辅助器,wp... 透视透视!德普之星辅助器,wpk显示有作弊,扑克教程(起初有挂);1.德普之星辅助器 ai辅助创建新...