我有一个使用Polymer的应用程序。在这个应用程序中,我有一个如下所示的组件:
我-component.html
<dom-module id="view-tests">
<template>
<table>
<tbody>
<template is="dom-repeat" items="{{ items }}" as="item">
<tr>
<td>[[ item.name ]]</td>
<td><item-status status="[[ item.status ]]"></item-status></td>
</tr>
</template>
</tbody>
</table>
<button on-click="bindClick">Bind</button>
</template>
<script>
Polymer({
is: "my-component",
properties: {
items: {
type: Array,
notify: true,
value: function() {
return [
new Item({ name:'Item 1', status:'In Stock' }),
new Item({ name:'Item 2', status:'Sold Out' })
];
}
},
},
bindClick: function() {
var items = items;
for (var i=0; i<items.length; i++) {
if (i === 1) {
items[i].status = 'In Stock';
}
}
}
});
</script>
</dom-module>
如上面的代码段所示,还有另一个组件item-status
。
项-status.html
<dom-module id="test-status">
<template>
<span class$="{{ statusClass }}">{{ status }}</span>
</template>
<script>
Polymer({
is: "item-status",
properties: {
status: {
type: String,
value: '',
observer: '_statusChanged'
}
},
_statusChanged: function(newValue, oldValue) {
if (newValue === 'In Stock') {
this.statusClass = 'green';
} else if (newValue === 'Sold Out') {
this.statusClass = 'red';
} else {
this.statusClass = 'black';
}
}
});
</script>
</dom-module>
初始数据绑定正常工作。但是,当我单击“绑定”按钮时,文本不会像我期望的那样更新。此外,文本颜色不会像我期望的那样改变。我有意识地var items = items;
,因为在我的真实代码中,有一个回调发生,我必须将项目传递给回调。我不确定是否有更好的方法。不过,我的观点仍未正确更新。
感谢您提供任何帮助。
答案 0 :(得分:0)
- 当我点击&#34; Bind&#34;按钮,文本不会像我期望的那样更新
醇>
要使其正常工作,您必须使用this.set(&#39; item.1.status&#39;,&#39; In Stock&#39;)。有关阵列绑定的更多详细信息,请阅读https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#array-binding。
- 此外,文字颜色不会像我期望的那样改变。
醇>
你只是在设置课程。你必须设计项目的样式。在项目状态中包含样式标记,如下所示
<style>
.red {
color: red;
}
.green {
color: green;
}
</style>
3.我有var items = items;故意,因为在我的真实代码中,有回调发生
我认为你不能在回调中为数组项设置值,并使聚合物观察者工作。如果您在您的方案中发布更多详细信息,则有人可能会帮助您。