简体   繁体   English

如何正确使用 object 数组从 axios 到 function 到外部 ZC1C425268E17385F1ABZA7

[英]How to properly use the object array from axios get function to outside function

I'm trying to get a data from axios get request to be used for q-table rows and I was able to get it and use it on v-for.我正在尝试从 axios get request 获取用于 q-table 行的数据,并且我能够获取它并在 v-for 上使用它。 However I was not able to use it outside the axios function as it shows as empty array.但是我无法在 axios function 之外使用它,因为它显示为空数组。

Here's my full code这是我的完整代码

<template>
  <div class="q-pa-md">
    <q-table
      title="Treats"
      :rows="rows" <<-- Was not able to use the data from axios since it returns an empty array -->>
      :columns="columns"
      row-key="name"
    />
    <div v-for="name in fetchUsers.data" :key="name.name">
    {{name.email}} <<-- Was able to use the data from axios -->
    </div>
  </div>
</template>

<script setup>
import { getCurrentInstance, ref } from 'vue'
const { $api } = getCurrentInstance().appContext.config.globalProperties // axios

const fetchUsers = ref([])

const users = () => {
  const usersB = []
  $api.get('users')
    .then(response => {
      fetchUsers.value = response.data
      const usersA = fetchUsers.value.data.map(obj => {
        return {
          name: obj.name,
          email: obj.email
        }
      })
      usersB.push(...usersA) // If I console.log(usersB) here, it shows a non empty array
    })
    .catch(error => {
      console.log(error)
    })
  console.log(usersB)
  return usersB
}

console.log(users()) // Shows zero array but shows there's a value like on below example
// []
// 0: {name: 'Eric', email: 'eric@eric.com'}
// 1: {name: 'John Lennon', email: 'john@beatles.com'}
// 2: {name: 'Eric', email: 'eric1@eric.com'}
// 3: {name: '', email: ''}

const columns = [
  {
    name: 'name',
    required: true,
    label: 'Dessert (100g serving)',
    align: 'left',
    field: row => row.name,
    format: val => `${val}`,
    sortable: true
  }
]

const rows = [ // => Main goal value after the object from axios are converted into array
  {
    name: 'Frozen Yogurt',
    calories: 159,
    fat: 6.0,
    carbs: 24,
    protein: 4.0,
    sodium: 87,
    calcium: '14%',
    iron: '1%'
  }
]

</script>

result of calling users()调用 users() 的结果

Am I missing a syntax on this?我错过了这方面的语法吗? I'm trying to understand the old related posts.我正在尝试了解旧的相关帖子。 However, it is still not working.但是,它仍然无法正常工作。

Array/List length is zero but Array is not empty 数组/列表长度为零但数组不为空

Your issue stems from the (incorrect) use of a promise.您的问题源于(不正确)使用 promise。 The promise executes asynchronously, that is after you return an empty array promise 异步执行,即在您返回一个空数组之后


const users = () => {
  const usersB = []
  $api.get('users')
    .then(response => {
      fetchUsers.value = response.data
      const usersA = fetchUsers.value.data.map(obj => {
        return {
          name: obj.name,
          email: obj.email
        }
      })
      usersB.push(...usersA) // <=== this executes later, when request is resolved
    })
    .catch(error => {
      console.log(error)
    })
  console.log(usersB)
  return usersB // <=== this executes first 
}

There are a few ways of handling properly.有几种正确处理的方法。 Here's an example with ref这是一个带有ref的示例

// define the `ref`
const users = ref([])

// load users function (though it doesn't need to be in encapsulated)
const loadUsers = () => {
  $api.get('users')
    .then(response => {
      fetchUsers.value = response.data
      const usersA = fetchUsers.value.data.map(obj => {
        return {
          name: obj.name,
          email: obj.email
        }
      })
      // update ref value
      users.value = [...usersA]
    })
    .catch(error => {
      console.log(error)
    })
}

// call the function
loadUsers()

in your template you can now use users which will be reactive, so when the API loads it will update, which will trigger a change.在您的模板中,您现在可以使用响应式users ,因此当 API 加载时,它将更新,这将触发更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM