vue w / axios应该使用从另一个get-request检索的变量获取请求

时间:2018-03-06 11:55:08

标签: javascript vue.js axios

当构建包含名为 fabmoment 的3D打印信息的组件时,我成功地使用$route.params填充了一个author-object和一个fabmoment-object信息,如下所示:

<script>
import SingleSummarized from './SingleSummarized'
// import Comments from '@/components/Comments/Multiple'
export default {
  name: 'Single',
  data () {
    return {
      author: null,
      fabmoment: null,
      tempLicenseID: null,
      license: null
    }
  },
  created () {
    this.$http.get(`/users/${this.$route.params.author_id}`)
        .then(request => { this.author = request.data })
        .catch(() => { alert('Something went wrong when trying to retrieve this user!') })
    this.$http.get(`/users/${this.$route.params.author_id}/fabmoments/${this.$route.params.fabmoment_id}`)
        .then(request => { this.fabmoment = request.data })
        .catch(() => { alert('Something went wrong when trying to retrieve the fabmoment attribute data!') })
    this.$http.get(`/licenses/${this.fabmoment.license_id`)
        .then(request => { this.license = request.data })
        .catch(() => { alert('Something went wrong when trying to retrieve the license!') })
  },
  components: {
    SingleSummarized
    // Comments
  }
}
</script>

在创建的部分中,您可以看到我也在尝试使用this.fabmoment.license_id检索fabmoment的许可证。它失败了。

tempLicenseID是个想法吗?因为我怀疑this.fabmoment尚未提供。我将如何使用它来使请求工作?还是其他任何更明智的解决方案?

1 个答案:

答案 0 :(得分:1)

您必须在检索fabmoment对象后提出许可证请求:

this.$http.get(`/users/${this.$route.params.author_id}/fabmoments/${this.$route.params.fabmoment_id}`)
    .then(request => { return this.fabmoment = request.data })
    .then( fabmoment => this.$http.get(`/licenses/${fabmoment.license_id`)
    .then(request => { this.license = request.data })
    .catch(() => { alert('Something went wrong when trying to retrieve the fabmoment attribute data!') })