Polymer dom-if:如何实现负面条件?

Kei*_*ith 4 polymer dom-if

我有一个Polymer元素,用于<template is="dom-if"...根据条件提供不同的HTML内容.

聚合物dom-if没有其他条件,因此需要一个负的if条件来模拟它.

像这样的东西:

<link href="https://polygit.org/components/polymer/polymer.html" rel="import">

<dom-module id="test-thing">
  <template>
    <template is="dom-if" if="{{title}}" restamp>
      <b>[[title]]</b>
    </template>
    <template is="dom-if" if="{{!title}}" restamp>
      <i>no title</i>
    </template>
  </template>
  <script>
    Polymer({
      is: 'test-thing',
      properties: {
        title: String
      }
    });
  </script>
</dom-module>

<div>
  With negative condition:
  <test-thing></test-thing>
</div>
<div>
  With positive condition:
  <test-thing title="Has Title"></test-thing>
</div>
Run Code Online (Sandbox Code Playgroud)

只有这不起作用 - 负面条件永远不会通过.

该如何实施?

Moj*_*ian 8

您必须为title属性使用默认空值:

  title:{type: String,value:''}
Run Code Online (Sandbox Code Playgroud)

像这样:

<link href="https://polygit.org/components/polymer/polymer.html" rel="import">

<dom-module id="test-thing">
  <template>
    <template is="dom-if" if="{{title}}" restamp>
      <b>[[title]]</b>
    </template>
    <template is="dom-if" if="{{!title}}" restamp>
      <i>no title</i>
    </template>
  </template>
  <script>
    Polymer({
      is: 'test-thing',
      properties: {
        title: {type: String,value:''}
      }
    });
  </script>
</dom-module>

<div>
  With negative condition:
  <test-thing></test-thing>
</div>
<div>
  With positive condition:
  <test-thing title="Has Title"></test-thing>
</div>
Run Code Online (Sandbox Code Playgroud)

  • Polymer不会使用尚未设置的变量呈现表达式.计算属性也以这种方式工作.[阅读更多](https://www.polymer-project.org/1.0/docs/devguide/observers#simple-observers). (2认同)