如何将对象字面量作为Polymer属性传递

8
为了在隔离环境中测试我的一些聚合物自定义元素,我希望能够传递JavaScript对象字面量作为一些属性的值,而这些属性通常是来自父元素。但我无法弄清如何实现这一点。请看以下示例代码。如果它按照我的期望工作,它会将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>

3个回答

9

只有在使用空哈希初始化 stuff 属性时,Polymer 才会将 JSON 文本转换为对象:

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

如果没有这个,stuff属性会被作为字符串传递。数组也是一样。


有没有想过在不知道属性名称的情况下如何实现这个? - posit labs
不要直接添加 {},而是使用已声明的属性和默认值功能。并且,请使用返回对象的函数,否则您元素的所有实例最终都将共享同一个对象。 - Overclocked

6
另一种方法是: myElem.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>

index.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>

Result

default_1 default_2  
1 2

基本上重复了上面的内容,但是有一个很好的例子。 - leeroya

3
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>

就像我最终基于这个解释来构建我的组件一样,我喜欢这个。+1 - leeroya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接