如何将对象文本作为聚合物属性传递

How to pass object literals as polymer attributes

本文关键字:聚合物 属性 对象 文本      更新时间:2023-09-26

为了单独测试我的一些聚合物自定义元素,我希望能够为一些通常来自父元素的属性传递js对象文字。我很难弄清楚如何做到这一点。请参阅此示例代码。如果它按照我想要的方式工作,它会在彼此旁边显示 1 和 2,但它不起作用。

<script src="http://www.polymer-project.org/webcomponents.js"></script>
<link rel="import" href="http://www.polymer-project.org/components/polymer/polymer.html">
<polymer-element name="my-element" attributes="stuff">
  <template>
    {{stuff.one}} {{stuff.two}}
  </template>
  <script>
    Polymer('my-element', {
      ready: function () {
        console.log(this.stuff);
      }
    });
  </script>
</polymer-element>
<my-element stuff='{"one": 1, "two": 2}'></my-element>

如果使用空哈希初始化 stuff 属性,则 Polymer 仅将 JSON 文本转换为对象:

Polymer('my-element', {
    stuff: {},
    ready: function () {
        console.log(this.stuff);
    }
});

如果没有这个,stuff属性将作为字符串传入。数组也是如此。

另一种方法:

我的埃莱姆.html

<link rel="import"
      href="http://www.polymer-project.org/1.0/samples/components/polymer/polymer.html">
<dom-module id="my-element">
    <template>
        <div> {{stuff.one}} {{stuff.two}} </div>
    </template>
    <script>
      Polymer({
          is: "my-element",
          properties: {
              stuff:{
                  type: Object,
                  value: {"one":"default_1","two":"default_2"}
              }
          }
      });
    </script>
</dom-module>

索引.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="http://www.polymer-project.org/1.0/samples/components/webcomponentsjs/webcomponents-lite.js"></script>
    <link rel="import" href="myElem.html">
  </head>
  <body>
    <my-element></my-element>
    <my-element stuff={"one":"1","two":"2"}></my-element>
  </body>
</html>

结果

default_1 default_2  
1 2
index.html
...
  <body unresolved fullbleed layout vertical>
     <my-post info='{"name":"Alex","id":"123"}' posts='[{"id":"456","name":"post1"},{"id":"789","name":"post2"}]'></my-post>  
  </body>
    ...
my-post.html 
    <link rel="import" href="../../bower_components/polymer/polymer.html">
    <polymer-element name="my-post" attributes="info posts" >
      <template>
       {{info.name}}
         <template repeat="{{post in posts}}">
              <br>   {{post.id}} - {{post.name}}
         </template>
      </template>
   <script>
    (function () {
      Polymer({
      ready: function() {
        this.info=JSON.parse(this.info)
        this.posts=JSON.parse(this.posts)
    },
   });
  })();
  </script>
</polymer-element>