[英]Programmatically setting property value on array item in Polymer
我有一個使用Polymer的應用程序。 在此應用程序中,我有一個如下所示的組件:
my-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
。
item-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;
故意是因為在我的真實代碼中,發生了回調,並且我必須將項目傳遞給回調。 我不確定是否有更好的方法。 盡管如此,我的觀點仍未正確更新。
感謝您提供任何幫助。
- 當我單擊“綁定”按鈕時,文本沒有按預期更新
為此,您必須使用this.set('item.1.status','In Stock')。 請閱讀https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#array-binding以獲得有關數組綁定的更多詳細信息。
- 此外,文本顏色不會像我期望的那樣變化。
您只是在設置課程。 您必須設置樣式。 在項目狀態中包含樣式標簽,如下所示
<style>
.red {
color: red;
}
.green {
color: green;
}
</style>
3.我有var個項=個項; 故意是因為在我的真實代碼中,發生了回調
我認為您不能為回調中的數組項設置值並使聚合物觀察器正常工作。 如果您在方案中發布更多詳細信息,則可能會有人幫助您。
工作的jsbin: http ://jsbin.com/yugofo/edit?html,控制台,輸出
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.