Polymer 1.0 传递 JSON 字符串作为属性

Polymer 1.0 passing JSON string as proprty

我带着新问题回来了,再次寻求专家帮助!

在我的 Polymer 0.5 项目中,我有一个 JSON 数组传递给 属性,如下所示:

<horizontal-barset max="3320000" data='[
{"title": "Annuals", "prevord": "1-15-2015",
  "ds": [
  {"subhead": "Last Year Sales", "value": "2960000", "className" : "last-year"},
  {"subhead": "YTD", "value": "1956000", "className" : "ytd"},
  {"subhead": "Previous Order", "value": "480000", "className" : "prev-order"}
  ]
},
{"title": "Perennials", "prevord": "1-15-2015",
  "ds": [
  {"subhead": "Last Year", "value": "540000", "className" : "last-year"},
  {"subhead": "YTD", "value": "2140000", "className" : "ytd"},
  {"subhead": "Previous Order", "value": "320000", "className" : "prev-order"}
  ]
},
{"title": "Totals", "prevord": "1-15-2015",
  "ds": [
  {"subhead": "Last Year", "value": "3320000", "className" : "last-year"},
  {"subhead": "YTD", "value": "1350000", "className" : "ytd"},
  {"subhead": "Previous Order", "value": "1700000", "className" : "prev-order"}
  ]
}
]'>
</horizontal-barset>

并且在元素中我初始化了 created 中的空数组,如下所示:

created: function(){
  this.data=[];
}

在 Polymer 1.0 中,属性现在以不同的方式编写:

properties: {
  max: {type: String},
  data: [] //(not sure this is the corrent approach! I also tried data: Object)
}

然后像 0.5 我尝试以类似的方式初始化空对象,但在 JavaScript 中出现 data is undefined(请参阅随附的屏幕截图)错误控制台。

这是我用来初始化 JSON 数组的片段:

created: function(){
  this.data = [];
}

迭代是这样写在元素里面的:

<template is="dom-repeat" items="{{data}}">
  <div class="rack-container">
    <p>{{item.title}}</p>
    <template is="dom-repeat" items="{{item.ds}}">
      <div class="rack">
        <div class="rack-bar">
          <div class="rack-head">
            {{item.subhead}}
          </div> 
          <!--<span style="width:{{ (row.value / max) * 100}}%;line-height:2em;" class="{{row.className}} rack-fill">&nbsp;</span>-->
          <div class="clear"></div>
        </div>
      <div class="rack-value">{{item.value}}</div>
      <div class="clear"></div>
  </div>
</template>
          </div>
      </template>

我怎样才能做到这一点?

您实际上是在正确的轨道上!下面是声明数组 属性:

的方法
properties: {
  max: {type: String},
  data: {
    type: Array, // Available property types are String, Number, Boolean, Array, and Object
    value: function () { return []; } // Default value
  }
}

但是,在您的数据绑定模板上,您必须确保标签内没有空格。基本上,你必须重写这一行

<div class="rack-head">
  {{item.subhead}}
</div> 

至此

<div class="rack-head">{{item.subhead}}</div> 

来源: