gpt4 book ai didi

javascript - Nuxt Js asyncData 返回值表现得很奇怪。

转载 作者:行者123 更新时间:2023-12-03 04:09:35 27 4
gpt4 key购买 nike

我正在开发一个 nuxt js/vue js 项目。在其中我必须调用多个 REST API。在页面组件中,我调用 asyncData() nuxt js API 来调用 REST api。

import { getCategories } from '~/api'
import { getProducts } from '~/api'


export default {

data() {
return {

}
},`



asyncData ({ req, params }) {
//-----------------PART 1-----------------------------
// var res1 = getCategories()
// var res2 = getProducts()

// return {
// res1,
// res2
// }
//-----------------PART 2-----------------------------
// return getCategories()
// return getProducts()


//----------------------------------------------
},



created() {

if(typeof(Storage) !== "undefined"){

if(!localStorage.getItem("cityName")){
this.$router.push('/')
}

} else{
console.log('This browser does not support local storage')
}

this.$store.dispatch('initFilters')


this.$store.dispatch('initCategories', this.categories)

//NOTICE HERE
// console.log(this.allProducts) //This one works on single return
// console.log(this.res1.allProducts) //This doesnot work on object return

},

}

当我尝试返回 getCategories()返回 getProducts()(代码中的第 2 部分)时,它会起作用并返回我想要的对象结果。

但是由于我需要这两个对象,所以我尝试将它们放入一个对象中并返回它们(第 1 部分),然后通过 console.log(this.res1.allProducts) 调用我没有得到想要的对象。

这是API代码

import axios from 'axios'
const API_ROOT = 'http://deligram.mg/rest/'
const API_VERSION = 'V1'
const MAGENTO_STORE = 'default'
const API_BASE = API_ROOT + '/' + MAGENTO_STORE + '/' + API_VERSION + '/'

const apiUrl = (path) => {
return API_BASE + path
}

const apiGet = (path) => {
return axios.get(apiUrl(path))
}

export function getCategories () {
return apiGet('categories')
.then((res) => {
return { categories: res.data }
})
}

export function getProducts () {
return apiGet('products?searchCriteria%5BcurrentPage%5D=10')
.then((res) => {
return { allProducts: res.data }
})
}

谁能告诉我我做错了什么?或者任何人都可以提出一种替代方法来在单个返回中获取两个对象?

最佳答案

我假设您的 API 方法返回一个 Promise。您应该使用 Promise.all 等待两个 Promise 都得到解决,然后返回一个包含 nuxt 应设置的数据的对象: p>

var res1 = getCategories()
var res2 = getProducts()
return Promise.all(re1, res2).then(function ([data1, data2]) {
return Object.assign({}, data1, data2)
})

生成的对象将如下所示:

{
categories: [ /* data from getCategories() */]
allProducts: [ /* data from getProducts () */ ]
}

关于javascript - Nuxt Js asyncData 返回值表现得很奇怪。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44385655/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com