Polymer 3 中的条件渲染

问题描述

我需要根据布尔变量 true 或 false 值呈现不同的 html。例如在反应中,我会在渲染函数的返回中做这样的事情:

{this.state.booleanValue ? "true" : "false"}

根据 booleanValue 的值,我得到两个不同的输出

我在 polymer 3 中尝试过,并首先声明了我的 bool 变量:

static get properties() {
    return {
      myBoolValue: {
        type: Boolean
      }
    };
  }

然后我尝试在我的模板/html中使用它

${this.myBoolValue ? "" : ""}

但是,代码无法识别 html 模板中的变量“this.myBoolValue”。怎么来的?我的模板的完整代码

static get template() {
    return html`
     
     <div>
        ${this.myBoolValue ? "true" : "false"}  // error,does not recognize "this.myBoolValue". 
   </div>

    `;

解决方法

如果 myBoolValue 的默认值是 false,您可以像这样更改属性和模板(如果您想使用 conditional templates,则必须导入 @polymer/polymer/lib/elements/dom-if.js。)

static get properties() {
  return {
    myBoolValue: {
      type: Boolean,value: false
    }
  };
}
static get template() {
  return html`
    <p>[[myBoolValue]]</p>

    // OR conditional templates:
    <template is="dom-if" if="{{myBoolValue}}">
      true
    </template>
    <template is="dom-if" if="{{!myBoolValue}}">
      false
    </template>
  `;
}

如果您不能或不想设置默认值,请像这样更改您的代码并使用 computed property

static get properties() {
  return {
    myBoolValue: {
      type: Boolean
    },computedBool: {
      type: String,computed: "_isTrue(myBoolValue)",value: false
    }
  };
}

static get template() {
  return html`
    <p>[[computedBool]]</p>

    <template is="dom-if" if="{{computedBool}}">
      true
    </template>
    <template is="dom-if" if="{{!computedBool}}">
      false
    </template>
  `;
}

_isTrue(a) {
  return a === true;
}