簡體   English   中英

__ob__:觀察者而不是我的對象數組( JSON.parse(JSON.stringify(obj)) NOT WORKING )

[英]__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的元素順序不同,因為它的數組元素是在FileReaderload事件上推送的,該事件根據文件大小在不同的時間發生。 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM