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

标签 javascript api vue.js vuex nuxt.js

我正在开发一个 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/

相关文章:

api - 使用Axios处理API调用错误

javascript - vue/vuetify 动态修改 v-text-field 属性

javascript - vuex中状态数组推送不是函数错误

vue.js - 如何在 buefy 中添加 b 表列?

javascript - 如何在组件 DOM 节点上切换类

api - semver 中补丁号递增的规则

javascript - 使用 Jest 模拟请求 header 模块

ruby-on-rails - 无法在 API Controller 中自动加载常量

javascript - 如何使用 gulp 在 javascript 文件中注入(inject)注释

javascript - 在 Angular2 中的路由之间传递数据