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}``,可以将结果呈现为一个文本节点。

相关内容

热门资讯

玩家必看教程!pokemmo脚... 玩家必看教程!pokemmo脚本辅助器,hh poker辅助器先试用,果然真的有挂(有挂方针)1、点...
一起来探讨!wepokerpl... 一起来探讨!wepokerplus开挂,德普之星怎么设置埋牌,其实是有挂(有挂助手)一起来探讨!we...
热点推荐!wepoker透视脚... 热点推荐!wepoker透视脚本网页,wepokerplus开挂,确实真的有挂(有挂教程)1、热点推...
玩家必备攻略!wepoker开... 玩家必备攻略!wepoker开脚本视频,hhpoker真能买到挂吗,一直存在有挂(有挂辅助)1、起透...
终于懂了!德扑圈有透视吗,微扑... 终于懂了!德扑圈有透视吗,微扑克数据分析,果然是有挂(有挂教学)1、下载好正确养号方法之后点击打开,...
玩家必备教程!hhpoker德... 玩家必备教程!hhpoker德州作弊,pokermaster脚本,真是存在有挂(证实有挂)运辅助工具...
总算明白!hhpoker德州透... 总算明白!hhpoker德州透视,pokermaster辅助器,总是是有挂(有挂透明挂)一、游戏安装...
一起来探讨!来玩德州破解器,w... 一起来探讨!来玩德州破解器,wepoker作弊视频,都是有挂(有挂秘笈)所有人都在同一条线上,像星星...
实测教程!sohoopoker... 实测教程!sohoopoker辅助,pokemmo脚本,本来是有挂(新版有挂)1、模拟器是什么优化,...
2024教程!pokermas... 2024教程!pokermaster脚本,htx矩阵wepoker辅助,竟然是有挂(讲解有挂)wep...