[英]Which is the best approach to push an object into an array? - push(obj) or push(JSON.parse(JSON.stringify(obj)))
[英]__ob__: Observer instead of my array of objects ( JSON.parse(JSON.stringify(obj)) NOT WORKING )
我需要按字母顺序输入文件,当我将文件从一个数组传递到另一个数组时,顺序混淆了。 这是获取文件的方法:
updatePreviews() {
if (this.plan.gallery == null || this.plan.gallery.length == 0) {
this.plan.gallery = [];
}
if (this.files?.length == 0) {
this.planImages = this.oldImages.filter((o) =>
this.planImages.map((o) => o.name).includes(o.name)
);
}
this.files.forEach((file) => {
const fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.addEventListener("load", () => {
if (
!this.planImages
.map((g) => g.name)
.includes(file.name)
) {
this.planImages.push({
name: file.name,
type: this.viewTypes[0],
url: fileReader.result,
description: "",
});
}
});
});
}
现在看看当我记录this.files时会发生什么顺序很好(第 417 行)
但是当我记录 this.planImages (我从 vue 调用的)时,这就是发生的事情。它们被包装到一个观察者中,并且顺序与文件数组不同。 这是我调用 this.planImages 显示的 vue 代码,它工作正常
<v-row v-for="(image, index) in this.planImages" :key="index">
<v-text-field
label="Name"
class="ma-4"
v-model="image.name"
readonly
full-width
></v-text-field>
<v-combobox
class="ma-4 mt-10"
label="View Type"
v-model="image.type"
:items="viewTypes"
></v-combobox>
<v-icon class="pt-4 pr-4" @click="deleteImage(index)"
>mdi-delete</v-icon
>
</v-row>
现在...我认为这是因为文件名有像“()”这样的特殊字符,但我不能应用任何排序方法,因为我无法访问任何东西,因为文件嵌套在观察者中。
我已经处理了一段时间了,以下是我尝试过的一些方法和结果:
我看到的最常见的解决方案是
const testJSON = JSON.parse(JSON.stringify(this.planImages));
console.log(testJSON);
这只是给我一个空数组
唯一对我有用的是:
this.planImages.__ob__ = new Object({});
这给了我这个正如你看到的,它给了我一个包含文件的数组(仍然混淆)但它打印了这个错误: Uncaught TypeError: ob.observeArray is not a function
我想不出办法解决这个问题,如果有人能告诉我为什么我无法找到这一切的根源,我将不胜感激
__ob__
是 Vue 反应性系统使用的内部属性,不应由您的代码修改。
this.planImages
的元素顺序不同,因为它的数组元素是在FileReader
的load
事件上推送的,该事件根据文件大小在不同的时间发生。 在this.planImages
看到的顺序可能是最小文件到最大文件。
要保留数组顺序,请将加载的文件插入到原始索引处的新数组中:
updatePreviews() {
⋮ 👇
this.files.forEach((file, index) => {
const fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.addEventListener("load", () => {
⋮ 👇
this.planImages[index] = {
name: file.name,
type: this.viewTypes[0],
url: fileReader.result,
description: "",
}
});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.