*ngIf equivalent in lit-element/polymer

huangapple go评论122阅读模式
英文:

*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`&lt;p&gt;something&lt;/p&gt;` : html`&lt;p&gt;something else&lt;/p&gt;`}

答案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`&lt;p&gt;something&lt;/p&gt;` : html`&lt;p&gt;something else&lt;/p&gt;`

And write it more efficiently as:

html`&lt;p&gt;${this.myBool ? &#39;something&#39; : &#39;something else&#39;}&lt;/p&gt;`

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

huangapple
  • 本文由 发表于 2020年1月6日 19:58:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/59611717.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定