在使用具有反应性 url - Vue.js 3 的 axios 操作结果之前,如何等待异步调用

How can I wait for asynchronous call before manipulating results using axios with reactive url - Vue.js 3

我有以下获取数据的代码。 urls 应该是反应式的,如果是改变一个新的调用完成。:

const apiClient = axios.create({
  baseURL: 'https://vue-http-demo-some-number.firebaseio.com',
  withCredentials: false,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application-json'
  }
});

function useFetch(getRelativeURL) {
  const data = ref(null);
  const error = ref(null);
  const isPending = ref(true);

  watchEffect(() => {
    apiClient.get(getRelativeURL())
      .then(response => {
        data.value = response.data;
      })
      .catch(err => {
        error.value = err;
      })
      .finally(() => {
        isPending.value = false;
      });
  });
  return {
    data,
    error,
    isPending
  }
}

和通话:

setup() {

  const books = [];
  const {data, error, isPending} = useFetch(() => '/books.json');

  for (const key in data.value) {
    for (const u in data.value[key]) {
      const book = {
        id: key,
        title: data.value[key][u].title,
        description: data.value[key][u].description,
      };
      books.push(book);
    }
  }

  return {
    books,
    error,
    isPending
  }
}

我的问题是来自 userFecth 的响应出现延迟,并且在我有非空数据之前就提取了书籍。我有什么选择可以保持 url 反应性和更新书籍。

你可以看到来自组合函数的 data :


import {watch} from 'vue'
setup() {

  const books = [];
  const {data, error, isPending} = useFetch(() => '/books.json');

 watch(()=>data,()=>{
   for (const key in data.value) {
     for (const u in data.value[key]) {
       const book = {
        id: key,
        title: data.value[key][u].title,
        description: data.value[key][u].description,
       };
       books.push(book);
     }
    }
  }
 ,{
 deep:true
 })

  return {
    books,
    error,
    isPending
  }
}