我需要按字母順序輸入檔案,當我將檔案從一個陣列傳遞到另一個陣列時,順序混淆了。這是獲取檔案的方法:
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>
現在...我認為這是因為檔案名有像“()”這樣的特殊字符,但我不能應用任何排序方法,因為我無法訪問任何東西,因為檔案嵌套在觀察者中。
I've been dealing with this for a while now and here are some of the things I tried and the result:
The most common solution I saw is
const testJSON = JSON.parse(JSON.stringify(this.planImages));
console.log(testJSON);
This just gives me an empty array back
The only thing that seemed to work for me was:
this.planImages.__ob__ = new Object({});
Which gives me this back As you see it gives me back an array with the files (Still mixed up) but it prints this error: Uncaught TypeError: ob.observeArray is not a function
I couldn't figure out a way out of this, if someone could please tell me why I can't get to the root of all this I would really appreciate it
uj5u.com熱心網友回復:
__ob__ 是 Vue 的反應式系統使用的內部屬性,不應手動修改。
的元素順序this.planImages不同,因為它的陣列元素是根據FileReader'load事件推送的,該事件根據檔案大小在不同時間發生。中看到的順序this.planImages可能是最小檔案到最大檔案。
要保留陣列順序,請將加載的檔案插入到原始索引處的新陣列中:
updatePreviews() {
?
this.planImages = []; ??
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: "",
}
});
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/328322.html
標籤:javascript typescript vue.js
