首页  >  问答  >  正文

无法通过 Axios 的 get 请求访问 Vue 中的数据

我是 vue 新手,我不明白我在这里做错了什么。

我有这个简单的组件:

<template>
    <template v-if="loading">
      Loading...
    </template>
    <template v-else>
      <div class="row">
          {{ row }}
      </div>
    </template>
  </template>

  <script>
    import { api } from 'src/boot/axios';
    import { useUserLoginStore } from 'src/stores/UserLoginStore';


    export default {

    async mounted() {
      this.loading = true

      try {
        const res = await api.get(`/v-cards/slug/${this.$route.params.slug}`, {
          headers: {
            Authorization: `Bearer ${useUserLoginStore().userToken}`,
          }
        });
        this.rows = await res.data
        this.loading = false
        console.log('rows', this.rows)
      } catch (error) {
        this.error = true
        console.log(error)
        this.loading = false
      }


    },

    data() {
      return {
        loading: false,
        row: [],
      }
    },
}

  </script>

但是当我渲染页面时,我只看到一个空数组。 api 调用没问题,因为我在控制台日志中看到了正确的数据。

P粉204079743P粉204079743375 天前589

全部回复(1)我来回复

  • P粉714844743

    P粉7148447432023-09-13 12:43:47

    您等待 res.data 有什么具体原因吗?您已经在等待上面的 api 调用响应。我相信删除 res.data 前面的等待应该可以解决您的问题。

    更改此行:

    this.rows = await res.data
    

    对此:

    this.rows = res.data
    

    这是假设 res.data 正是您期望的数组。并且不嵌套在另一个对象属性中。

    此外,在模板中,您应该使用rows而不是row

    回复
    0
  • 取消回复