【问题标题】:Undefined data variable Vue.js when using axios使用 axios 时未定义的数据变量 Vue.js
【发布时间】:2022-09-23 01:08:30
【问题描述】:

这让我发疯了。

我正在将 axios 响应中的值分配给我的 vue 数据,如下所示:

mounted() {
  axios
  .get(\'/campaigns/new.json\')
    .then(response => (
      this.kits = response.data[0].kits,
     )
  )

我可以使用 vue 开发人员工具看到我的 this.kits 有一个包含 8 个项目的数组(正确)

当我之后尝试使用this.kits 或使用console.log(this.kits) 时,我得到了未定义或空数组.

我到底在想什么?请帮忙。谢谢

mounted() {
  axios
  .get(\'/campaigns/new.json\')
    .then(response => (
      this.kits = response.data[0].kits,
      this.kitProducts = response.data[0].kitproducts,
      this.products = response.data[0].products,
      this.boxes = response.data[0].boxes,
      this.categories = response.data[0].categories,
      this.extras = response.data[0].extras,
      this.isCurrentUser = response.data[0].user,
      this.giftpacks = response.data[0].giftpacks
     )
  )
  console.log(this.kits)

console.log(this.kits) 将输出:

  • 你在哪里做 console.log ?
  • @y.kaf。在我的mounted() vue 函数中
  • 我认为在请求完成之前正在调用console.log,尝试将其放在异步函数中,基本的异步/等待问题

标签: javascript vue.js


【解决方案1】:

尝试等待您的数据。将 API 调用移至方法:

methods: {
  getData() {
    axios
     .get('/campaigns/new.json')
     .then(response => (
     this.kits = response.data[0].kits,
    )
  }
}

然后在挂载的钩子中:

async mounted() {
  await this.getData()
  console.log(this.kits)
}

【讨论】:

    【解决方案2】:

    您的console.log 在promise 请求启动后立即执行,您必须将它放在then 块内的末尾,或者如Nicola 所说,使用async await

    【讨论】:

      猜你喜欢
      • 2021-10-15
      • 2019-02-06
      • 1970-01-01
      • 2019-03-11
      • 2018-12-07
      • 2021-11-14
      • 1970-01-01
      • 2016-05-06
      相关资源
      最近更新 更多