英文:
*ngIf equivalent in lit-element/polymer
问题
我正在寻找在lit-element中实现基于条件的HTML,需要类似Angular提供的*ngIf的功能。
我可以根据条件渲染不同的HTML,但如果能通过条件来完成会更好。
英文:
I'm looking to implement condition based HTML in lit-element and need something like *ngIf which Angular provides.
I could render different HTML based on conditions but it will be great if it can be done with condition.
答案1
得分: 5
你可以使用纯粹的JavaScript。在官方文档中有详细说明。
示例:
${this.myBool ? html`<p>something</p>` : html`<p>something else</p>`}
英文:
You can use plain Javascript. Explained well in official documentation
Example:
${this.myBool ? html`<p>something</p>` : html`<p>something else</p>`}
答案2
得分: 1
扩展Kuba的回答,尽量尽可能具体地使用lit-html条件,因为条件的范围越广,当条件发生变化时需要重新渲染的模板部分就越多。例如,你可以将官方文档中给出的示例:
this.myBool ? html`<p>something</p>` : html`<p>something else</p>`
更高效地编写为:
html`<p>${this.myBool ? 'something' : 'something else'}</p>`
这个小改变可能不会产生太大影响,但当你能够减少组件层级的重新渲染次数时,效果就会逐渐显现。
要更详细地了解lit-html
如何处理模板渲染,请参考:https://lit-html.polymer-project.org/guide/concepts#template-creation
英文:
Expanding on Kuba's answer, it's good to be as specific as possible with lit-html conditions, as the more broad-scoped your condition is, the more of the template that needs to be rerendered when the condition changes. For example, you can make the example given in the official documentation:
this.myBool ? html`<p>something</p>` : html`<p>something else</p>`
And write it more efficiently as:
html`<p>${this.myBool ? 'something' : 'something else'}</p>`
This little change here doesn't change much, but when you can reduce the amount of rerendering of layers of components, it starts to add up.
For a more thorough explanation of how lit-html
handles template rendering, see: https://lit-html.polymer-project.org/guide/concepts#template-creation
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论