如何使用vue js同步数据中的id,并到达id对应的name?

How can I synchronize the ids in the data using vue js and reach the name corresponding to the id?

我正在处理的项目中有两个不同的端点。其中一个端点(类别)为我提供了类别名称和 ID 值,而另一个(产品)仅为我提供了类别 ID 值。我想从两个端点提取id值,并将id值相等的字段的类别部分的id值对应的名称添加到产品部分。

我使用下面的for循环进行了同步,然后将其同步到产品的Category名称,但是代码太多并且无法稳定运行。我所说的稳定是指数据有时会出现有时不会,它也不会给出任何错误。你觉得我怎样才能写得更短更稳?

数据:

    products: {
  items: [{ categoryName: '' }],

},

cretated(){

 fetch('example/products')
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    this.products = data;
  });

fetch('example/categories')
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    this.categories = data;
    this.pushNametoCategoryNames();
  });
}

methods() {       
pushNametoCategoryNames() {
      for (let i = 0; i < this.products.items.length; i++) {
        for (let j = 0; j < this.categories.length; j++) {
          console.log(this.products);
          console.log(this.categories[j]);
          if (this.products.items[i].categoryId == this.categories[j].id) {
            this.products.items[i].categoryName = this.categories[j].name;
          }
        }
      }
    },
    }

您永远无法保证 this.pushNametoCategoryNames() 在两次 fetch 调用之后都会 运行,除非您从 then 调用第二个 fetch首先 fetch,或使用 async-await.

方法一

   fetch('example/products')
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        this.products = data;
         fetch('example/categories')
         .then((response) => {
            return response.json();
          })
         .then((data) => {
         this.categories = data;
            this.pushNametoCategoryNames();
         });
      });

方法二

async cretated(){
   this.products = await (await fetch('example/products')).json();
   this.categories = await (await fetch('example/categories')).json();
   this.pushNametoCategoryNames();
}

方法 3 (Promise.all)

cretated(){
   Promise.all([fetch('example/products'), fetch('example/categories')]).then(values => {
      Promise.all([values[0].json(), values[1].json()]).then(data => {
           this.products = data[0];
           this.categories = data[1];
           this.pushNametoCategoryNames();
      });
   });
   this.pushNametoCategoryNames();
}

您可以使用 map 并等待回复:

new Vue({
  el: "#demo",
  data() {
    return {
      products: [],
      categories: []
    }
  },
  async mounted(){
    await fetch('https://jsonplaceholder.typicode.com/posts/')
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        this.products = data;
      });
    await fetch('https://jsonplaceholder.typicode.com/users/')
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        this.categories = data;
      });
    this.pushNametoCategoryNames();
  },
  methods: {       
    pushNametoCategoryNames() {
      this.products = this.products.map(p => {
        const cat = this.categories.find(c => p.userId === c.id).username
        cat ? p.CATNAME = cat : p.CATNAME = 'EMPTY'
        return { ...p }
      })
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  {{products}}
</div>