Home  >  Q&A  >  body text

Unable to access data in Vue through Axios' get request

I'm new to vue and I don't understand what I'm doing wrong here.

I have this simple component:

<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>

But when I render the page, I only see an empty array. The api call is fine as I see the correct data in the console log.

P粉204079743P粉204079743375 days ago587

reply all(1)I'll reply

  • P粉714844743

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

    Is there any specific reason why you are waiting for res.data? You are already waiting for the response from the api call above. I believe deleting res.data and waiting in front should solve your problem.

    Change this line:

    this.rows = await res.data
    

    Regarding:

    this.rows = res.data
    

    This is assuming res.data is exactly the array you expect. and not nested within another object property.

    Also, in templates you should use rows instead of row

    reply
    0
  • Cancelreply