首先你应该在这里使用 Nuxt.js 官方提供的 Axios 模块,https://github.com/nuxt-community/axios-module。它们使 Axios 和 Nuxt.js 之间的集成变得更加容易。
Axios 使用 Promise,因此您可以轻松地使用链接方法来完成它。假设你想从/get/product 获取信息,数据来自你在http://****/getItems?userid=5&clientid=10 之前提到的网址,你可以像这样轻松地做到这一点
this.$axios.$get('/getItems?userid=5&clientid=10')
.then(data => {
// You can use your data received from first request here.
return this.$axios.$post('/get/product', {
id: data.id,
clientId: data.clientId
})
})
.then(data => {
// You can use your data received from second request here.
console.log(data)
})
说明
这部分,
this.$axios.$get('/getItems?userid=5&clientid=10')
axios 将从提供的 url 中获取数据,当接收到数据时,我们可以在 then() 块中使用它,因为它接受回调作为参数。
.then(data => {
// You can use your data received from first url here.
...
})
之后,如果您想使用您的数据,您可以轻松地再次返回 axios 请求并使用您想要发送的正确参数。
return this.$axios.$post('/get/product', {
id: data.id,
clientId: data.clientId
})
您可以再次使用从 then() 块中的第二个 axios 请求接收到的数据。
.then(data => {
// You can use your data received from second request here.
console.log(data)
})
更新
好的,根据下面评论部分的说明。我们可以在第一个动作中返回 axios 承诺,然后在第二个方法中我们可以调度第一个动作,
actions: {
callFirst ({ commit }) {
return this.$axios.$get('/get/first')
.then(firstResult => {
commit('SET_FIRST', firstResult)
return firstResult
})
},
callSecond ({ dispatch, commit }) {
return dispatch('callFirst').then(firstResult => {
return this.$axios.$post(`/get/${firstResult.userId}`)
.then(secondResult => {
commit('SET_SECOND', secondResult)
return secondResult
})
})
}
}
使用这种方式,您只需将callSecond() 操作放在您想要获取第二个数据的任何位置。而且您也不需要将callFirst() 操作放在default.vue 上。