问题
I have a data-bound array (dom-repeat
) in a custom Polymer element, and I need to push new data into the array. It's not displaying the items, even though it knows 2 elements have been added. What am I missing here?
jsFiddle
<link rel="import" href="../../bower_components/polymer/polymer.html">
<dom-module id="main-element">
<template>
<ul>
<template is="dom-repeat" items="{{people}}">
<li>{{item.first}}</li>
</template>
</ul>
</template>
<script>
(function() {
'use strict';
Polymer({
is: 'main-element',
properties: {
people: {
type: Array,
value: function() {
return [];
}
}
},
ready: function() {
// Mock data retrieval
this.people.push({"first": "Jane", "last": "Doe"});
this.people.push({"first": "Bob", "last": "Smith"});
}
});
})();
</script>
回答1:
Use Polymer's array mutation methods when pushing items into the array:
this.push('people', {"first": "Jane", "last": "Doe"});
this.push('people', {"first": "Bob", "last": "Smith"});
<head>
<base href="https://polygit.org/polymer+1.7.0/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="polymer/polymer.html">
</head>
<body>
<main-element></main-element>
<dom-module id="main-element">
<template>
<ul>
<template is="dom-repeat" items="{{people}}">
<li>{{item.first}}</li>
</template>
</ul>
</template>
<script>
HTMLImports.whenReady(function() {
'use strict';
Polymer({
is: 'main-element',
properties: {
people: {
type: Array,
value: function() {
return [];
}
}
},
ready: function() {
// Mock data retrieval
this.push('people', {"first": "Jane", "last": "Doe"});
this.push('people', {"first": "Bob", "last": "Smith"});
}
});
});
</script>
</dom-module>
</body>
codepen
来源:https://stackoverflow.com/questions/40622982/pushing-to-data-bound-array-used-in-dom-repeat-polymer