【问题标题】:build a nested array from multiple axios requests on Vuejs从 Vuejs 上的多个 axios 请求构建嵌套数组
【发布时间】:2020-05-10 10:13:12
【问题描述】:

我是 Vuejs 的新手,我不知道如何从 2 个 axios 请求构建嵌套数组,我知道有更好的方法来实现目标......使用这段代码我构建了 2 个单独的数组,一个用于productList(包含单个商店的所有产品),一个用于shopName(包含所有shop_urls)。我需要使用 array.map 进行嵌套请求,因为我想为每个 shop_url 构建一个产品数组

import axios from 'axios';

    export default 
    {
        name: 'Product',

        data: () => ({
            key: 'mySecretKey',
            productsList: [],
            shopName: [],
            errors: [],
        }),

          mounted() {
            axios.get('https://shop.domain.org/api/shop_urls?display=full&output_format=JSON', {                
                auth: {
                    username: this.key
                },
        }) 
        .then(response => response.data.shop_urls.map((val) => {
            this.shopName.push(val.virtual_uri)
            axios.get('https://shop.domain.org/' + val.virtual_uri + '/api/products?display=full&output_format=JSON', {                
                auth: {
                    username: this.key
                },
            })
            .then(response => this.productsList.push(response.data.products))
            .catch(e => this.errors.push(e))

        }))
    }
}

回应:

【问题讨论】:

  • 是否可以在服务器端处理它以防止发送请求两次?服务器端的响应可以是对象数组,如{ 'val' : val, 'products': products }
  • 不,也许是 prestashop API 网络服务

标签: vue.js request axios


【解决方案1】:

在我看来你可以使用

this.$set(this.productsList, val.virtual_uri, response.data.products)

那会创造

productsList: [
    "whateverthevirtualuriwas": [
        ...response.data.products
    ]
]

如果不了解数据如何到达以及您如何使用它,很难说,但希望这会有所帮助。

回复问题编辑 好的,不需要将 shopName 和 productsList 放入数据 imo 中。只是合并后的数组。

// in your data: mergedArray: [ ]

for (let index in shopName) {
    const uri = shopName[index]
    const products = productList[index]

    this.$set(this.mergedArray, uri, products)
}

【讨论】:

  • 已编辑以匹配。
  • 谢谢你的朋友,在你的帮助下,我发现:.then(response => this.productsList.push({name: val.virtual_uri, items: response.data.products}))
猜你喜欢
  • 2019-04-20
  • 2020-01-03
  • 2020-06-21
  • 2018-06-29
  • 2019-09-07
  • 2019-09-19
  • 2019-01-06
  • 2020-05-03
  • 2019-02-28
相关资源
最近更新 更多