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代打辅助(详细辅助工具)1、wepoker私人...
透视规律!aapoker ai... 透视规律!aapoker ai插件(透视)aapoker透视脚本入口,曝光教程(有挂脚本)1、aap...
透视新版!wepoker私人局... 透视新版!wepoker私人局可以透视,wepoker辅助器(详细代打辅助机器人);1、全新机制【w...
透视玄学!aapoker透视脚... 透视玄学!aapoker透视脚本下载(透视)aapoker辅助插件工具,教你攻略(有挂介绍)1、实时...
透视挂透视!wepoker线上... 透视挂透视!wepoker线上大神,wepoker辅助软件价格(详细购买模拟器);1)wepoker...
透视好友!aapoker真的假... 透视好友!aapoker真的假的(透视)aapoker怎么选牌,插件教程(有挂细节)1、首先打开aa...
透视了解!淘宝买wepoker... 透视了解!淘宝买wepoker透视有用吗,wepokerplus作弊(详细有透视功能)1、这是跨平台...
透视脚本!aapoker透视脚... 透视脚本!aapoker透视脚本下载(透视)aapoker如何设置胜率,解密教程(有挂揭秘)1、超多...
透视透视!wepoker可以开... 透视透视!wepoker可以开透视吗,wepoker作弊视频(详细辅助器);wepoker可以开透视...
透视软件!aapoker真的假... 透视软件!aapoker真的假的(透视)aapoker怎么拿好牌,可靠教程(有挂脚本)1)aapok...