为什么聚合物 属性 绑定需要在我的模板中添加标签?

Why does the polymer property binding need a tag in my template?

我想了解 Polymer 如何在自定义元素的模板中呈现属性。我看到一些我无法解释的行为,其中某些属性在一种情况下呈现(当被标签包围时),但在另一种情况下不呈现(当模板中不存在标签时)。为了演示我写这个 Plunker 的行为:

http://plnkr.co/WHYZKrjMMTMckw4X6p4Q

基本上我所做的是编写了以下自定义元素:

<link rel="import" href="http://www.polymer-project.org/1.0/samples/components/polymer/polymer.html">
<dom-module id="characters-label">
  <style>
  </style>
  <template>
    This has {{ncharacters}} characters!
  </template>
</dom-module>
<script>
  Polymer({
    is: "characters-label",
    properties: {
      ncharacters: {
        type: String,
        value: '6'
      }
    }
  });
</script>

我在 index.html 文件中这样使用它:

<!DOCTYPE html>
<html>

  <head>
    <script data-require="polymer@1.0.0" data-semver="1.0.0" src="http://www.polymer-project.org/1.0/samples/components/webcomponentsjs/webcomponents-lite.js"></script>
    <script data-require="polymer@1.0.0" data-semver="1.0.0" src="http://www.polymer-project.org/1.0/samples/components/polymer/polymer.html"></script>
    <link rel="import" href="characters-label.html" />
  </head>

  <body>
    <p>This is before my label</p>
    <div>
      <characters-label></characters-label>
    </div>
    <p>This is after my label</p>
  </body>

</html>

结果没有在 HTML 中呈现值“6”,而是我得到了模板的文字内容:

这是我的标签之前
这有 {{ncharacters}} 个字符!
这是在我的标签之后

但是,如果我将自定义元素的模板更改为:

<template>
  This has <b>{{ncharacters}}</b> characters!
</template>

那么结果如预期:

这是我的标签之前
这有 6 个字符!
这是在我的标签之后

这是正常行为吗?

是的,一切正常。参见 https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#binding-to-text-content

To bind to a child element’s textContent, you can simply include the annotation inside the child element. The binding annotation must currently span the entire content of the tag:

String concatenation is not supported inside a tag, and the tag can’t contain any whitespace: