我尝试在dom-repeat
帮助器中使用计算属性,但在我单击按钮后立即抛出异常(请参阅下面的代码,包版本:sdk: 0.12.2
,polymer: 1.0.0-rc.5
,polymer_interop: 1.0.0-rc.4+1
)。可能有什么问题?当我用{{computedItems}}
替换{{items}}
时,一切正常。
class Item extends JsProxy{
@reflectable
String a="aaa aaa";
@reflectable
String b="bbb bbb";
Item(this.a, this.b);
}
@PolymerRegister('main-app')
class MainApp extends PolymerElement {
@Property(computed:"getItems(items.*)")
List<Item> computedItems;
@property
List<Item> items = [];
@property
String inp = '';
MainApp.created() : super.created();
@reflectable
List<Item> getItems(_) {
return items;
}
@reflectable
void onTap(Event ev, Map details) {
add("items", new Item(inp, 'aa'));
set("inp", "");
}
}
和html
文件:
<dom-module id="main-app">
<template>
<paper-input value="{{inp}}"> </paper-input>
<paper-button raised on-tap="onTap">add to list</paper-button>
<template is="dom-repeat" items="{{computedItems}}">
<div style="color:red">
<span>[[item.a]]</span>
<span>[[item.b]]</span>
</div>
</template>
</template>
</dom-module>
答案 0 :(得分:1)
你可以这样做:
@PolymerRegister('app-element')
class AppElement extends PolymerElement {
AppElement.created() : super.created();
@property
List<Item> computedItems;
@property
List<Item> items = [];
@Observe('items.*')
void computeItems([_, __]) {
set('computedItems', items.toList());
// .toList() creates a copy, otherwise Polymer wouldn't
// recognize it as a change
// this works as well
// set('computedItems', null);
// set('computedItems', items);
}
@property int itemsChangeIndicator = 0;
@property
String inp = '';
@reflectable
List<Item> getItems(_) {
return items;
}
@reflectable
void tapHandler(dom.Event ev, Map details) {
add("items", new Item(inp, 'aa'));
set("inp", "");
}
}
(我重命名为onTap
,因为此命名方案很容易与元素中的事件流getter冲突,如onClick
)