项目作者: prashantk0001

项目描述 :
Expressions for IF/ELSE in LWC
高级语言: JavaScript
项目地址: git://github.com/prashantk0001/lwc-if-expressions.git
创建时间: 2020-11-22T05:12:37Z
项目社区:https://github.com/prashantk0001/lwc-if-expressions

开源协议:MIT License

下载


lwc-if-expressions

  1. <c-lwc-if condition="(this.a == this.b) && (this.c == 6 || this.b == 'easypeasy')" scope={scope}>
  2. <div slot="if">
  3. IFFFFFFFFFFFFFFFFF
  4. </div>
  5. <div slot="else">
  6. ELSEEEEEEEEEEEEEE
  7. </div>
  8. </c-lwc-if>

Does it look more readable? let’s take a deeper look:

Write expressions in component definition to handle complex rendering scenarios without learning a new expression language.

With Visualforce & Aura, developers had luxury to render HTML based on expressions, Eg. {!A == B}
While Lightning web component needs the use of individual javascript get properties to achieve similar feats, here’s an example how you can natively achieve this:

In template:

  1. <template if:true={decision}>
  2. print this
  3. </template>

In JS Controller:

  1. get scope(){
  2. return this.a == this.b;
  3. }

the above example bounds you to implement multiple get properties within js controller.

Now lets rewrite the same using lwc-if-expressions

In template:

  1. <c-lwc-if condition="this.a == this.b" scope={scope}>
  2. <div slot="if">
  3. IFFFFFFFFFFFFFFFFF
  4. </div>
  5. <div slot="else">
  6. ELSEEEEEEEEEEEEEE
  7. </div>
  8. </c-lwc-if>

In JS Controller:

  1. get scope(){
  2. return {
  3. a : this.a,
  4. b : this.b
  5. }
  6. }

So for complex,multiple rendering scenarios we only need to create a single scope get() property which would contain all the decision making props within the expression, which allows you to write expressions within the templates and makes code more readable & easy to implement.

Get Started:

You’d find a working example for lwc-if-expressions in the example module.