我正在尝试使用以下代码从iron-list
删除项目。
<iron-list id="list" items="[[items]]" as="item"
selected-items="{{selectedItems}}"
selection-enabled multi-selection>
<template>
<my-item item="[[item]]" on-tap="_onItemTap"></my-item>
</template>
</iron-list>
...
_onItemTap: function(e) {
this.items.splice(e.model.index, 1);
}
答案 0 :(得分:2)
See this answer for specific syntax contributing to the problem
http://jsbin.com/qefemoloxi/1/edit?html,console,output<!doctype html>
<head>
<meta charset="utf-8">
<base href="https://polygit.org/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link href="polymer/polymer.html" rel="import">
<link href="paper-button/paper-button.html" rel="import">
<link href="iron-list/iron-list.html" rel="import">
</head>
<body>
<dom-module id="x-element">
<template>
<style>
iron-list {
height: 100vh;
}
</style>
<iron-list id="list" items="[[items]]" as="item">
<template>
<paper-button on-tap="_deleteItem">[[item.name]]</paper-button>
</template>
</iron-list>
</template>
<script>
(function(){
Polymer({
is: "x-element",
properties: {
items: {
type: Array,
value: function() {
return [
{ 'name':'foo' },
{ 'name':'bar' },
{ 'name':'qux' },
{ 'name':'baz' },
{ 'name':'quux'}
]
}
}
},
_deleteItem: function(e) {
console.log(e.model.index);
this.splice('items', e.model.index, 1);
this.$.list.fire('resize');
}
});
})();
</script>
</dom-module>
<x-element></x-element>
</body>
答案 1 :(得分:0)
A summary of this page建议this documentation as follows:
题app.removeItem = function(index) {
app.data.splice(index, 1);
console.log("Removing " + index);
document.querySelector('#tobuy').fire('resize');
};
答复
document.querySelector('#tobuy').push('items', {name: "Foo"})
然后你不需要调用resize。
参考:https://www.polymer-project.org/1.0/docs/devguide/properties.html#array-observation
答案 2 :(得分:0)
This documentation on array mutation provides the following boilerplate code:
定制element.html<dom-module id="custom-element">
<template>
<template is="dom-repeat"></template>
</template>
<script>
Polymer({
is: 'custom-element',
addUser: function(user) {
this.push('users', user);
},
removeUser: function(user) {
var index = this.users.indexOf(user);
this.splice('users', index, 1);
}
});
</script>
</dom-module>
将此应用于此案例:
我-element.html// As a syntactical matter, replace the following line
// this.items.splice(e.model.index, 1);
// With this line
this.splice('items', e.model.index, 1);
this.$.list.fire('resize');
然而,此解决方案的一个问题是它会删除iron-list
中的最后一项,而不是预期索引处的项目。换句话说,它的行为就像人们期望的那样this.items.pop()
。
它还会抛出以下奇怪的错误消息:
的console.logUncaught TypeError: <item> should be a valid item
答案 3 :(得分:0)
See this answer for full code solution
这里的问题是由于我的item.html
文件正在设置并显示item.
属性之外的属性。因此,当调用iron-list.(this.)splice('items', e.model.index, 1);
数组变异方法时,不会从DOM中删除非item
属性。
示例:
我的列表,item.htmlthis.set( 'name', this.item.foo.bar.qux); // This syntax caused the problem
this.set('item.name', this.item.foo.bar.qux); // This fixed the problem
我的铁list.html
this.splice('items', e.model.index, 1);