【问题标题】:__ob__: Observer instead of my array of objects ( JSON.parse(JSON.stringify(obj)) NOT WORKING )__ob__:观察者而不是我的对象数组( JSON.parse(JSON.stringify(obj)) NOT WORKING )
【发布时间】:2021-12-05 19:33:33
【问题描述】:

我需要按字母顺序输入文件,当我将文件从一个数组传递到另一个数组时,顺序会混淆。 这是获取文件的方法:

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 时会发生什么 The order is fine(第 417 行)

但是当我 记录 this.planImages (我从 vue 调用) This is what happenes 它们被包装到观察者中,并且顺序与文件数组不同。 这是我调用 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({});

Which gives me this back 如您所见,它给了我一个包含文件的数组(仍然混淆),但它会打印此错误: 未捕获的类型错误:ob.observeArray 不是函数

我想不出办法解决这个问题,如果有人可以告诉我为什么我无法找到这一切的根源,我将不胜感激

【问题讨论】:

  • 请阅读How to Ask,其中指出“请勿发布代码、数据、错误消息等的图像 - 将文本复制或输入到问题中。”

标签: javascript typescript vue.js


【解决方案1】:

__ob__ 是 Vue 响应式系统使用的内部属性,不应手动修改。

this.planImages 的元素顺序不同,因为它的数组元素是在FileReaderload 事件上推送的,该事件根据文件大小在不同时间发生。在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: "",
      }
    });
  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2019-03-23
    • 2014-09-11
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 2020-10-18
    相关资源
    最近更新 更多