gpt4 book ai didi

polymer - 同一 polymer 元素的多个实例会导致所有这些元素的行为

转载 作者:行者123 更新时间:2023-12-04 17:32:57 26 4
gpt4 key购买 nike

我有一个简单的元素,它只允许您一次选择一个本地文件,然后将所选文件显示为您可以删除的项目,如下所示:
enter image description here

该组件本身工作得很好,问题是我在同一页面中有另一个相同类型的组件,但在不同的父元素(和隐藏)内。如果我在第一个文件选择器上选择 n 个文件,然后切换到查看另一个父组件,则第二个文件选择器在其中显示与第一个选择的文件相同的文件。

如果我将此文件组件中的两个放在同一个父元素中,则在其中一个文件中选择一个文件不会在另一个文件中显示相同的文件,但是从其中任何一个中删除文件会使组件文件数组属性(其中我存储每个选定的文件)在它们两个中都更短,最终导致无法从其中一个中删除项目。

我假设我的问题在某种程度上与封装有关,但不知道为什么。这是我的组件代码:

<dom-module id="custom-file-input">
<style>
...
</style>
<template>
<div class="horizontal layout flex relative">
<button class="action" on-click="butclick" disabled$="{{disab}}">{{restexts.CHOOSEFILE}}</button>
<div id="fakeinput" class="flex">
<template is="dom-repeat" items="{{files}}" as="file">
<div class="fileitem horizontal layout center">
<span>{{file.0}}</span><iron-icon icon="close" class="clickable" on-click="removeFile"></iron-icon>
</div>
</template>
</div>
<input id="fileinput" type="file" on-change="fileChanged" hidden />
</div>
</template>
<script>
Polymer({
is: "custom-file-input",
properties: {
files: {
type: Array,
value: []
},
currentFile: {
type: Object,
value: {}
},
disab: {
type: Boolean,
value: false,
reflectToAttribute: true,
notify: true
},
restexts: {
type: Object,
value: JSON.parse(localStorage['resourcesList'])
}
},
fileChanged: function (e) {
this.currentFile = e.currentTarget.files[0];
var elem = this;

var fr = new FileReader();
fr.readAsArrayBuffer(this.currentFile);
fr.onload = function () {
[...convert file to string64...]
elem.push('files', [elem.currentFile.name, string64]);
};
},
removeFile: function (e) {
for (var i = 0; i < this.files.length; i++) {
if (this.files[i] == e.model.file) {
this.splice('files', i, 1);
break;
}
}
},
butclick: function () {
this.$.fileinput.click();
}
});
</script>
</dom-module>

最佳答案

When initializing a property to an object or array value, use a function to ensure that each element gets its own copy of the value, rather than having an object or array shared across all instances of the element.



来源: https://www.polymer-project.org/1.0/docs/devguide/properties.html#configure-values
{
files: {
type: Array,
value: function() { return []; }
},
currentFile: {
type: Object,
value: function() { return {}; }
},
restexts: {
type: Object,
value: function() { return JSON.parse(localStorage['resourcesList']); }
}
}

关于polymer - 同一 polymer 元素的多个实例会导致所有这些元素的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37065801/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com