Vue 组合 Api .value returns null

Vue Composition Api .value returns null

我有一个像这样的“可组合”axios 函数

export const useFetch = (url: string, config: any = {}) => {
  const data = ref(null)
  const status = ref()
  const error = ref(null)
  const loading = ref(false)
  const fetch = async () => {
    loading.value = true
    error.value = null
    try {
      const result = await service.request({
        url,
        ...config
      })
      status.value = result.status
      data.value = result.data
    } catch (ex) {
      error.value = ex
    } finally {
      loading.value = false
    }
  }
  fetch()
  return { status, error, data, loading }
}

在像user.vue这样的单独文件中,我这样调用useFetch

  setup() {
    const { data, error } = useFetch(
      'https://jsonplaceholder.typicode.com/po3sts/1',
      {
        method: 'get'
      }
    )
    console.error(error)
    console.error(error.value)
    return { data, error }
  }

我的问题是当我console.error(错误)时,我可以清楚地看到

Object { value: Getter & Setter }
value: Error: Request failed with status code 404

但如果我这样做 console.error(error.value),它 returns 无效。

关于如何获得 error.value 的任何提示?

console.error(error.value) 此时输出实际值,而 console.error(error) 通过引用将对象传递给控制台并允许稍后访问更新的对象属性,这是什么引用模式的用例地址。

useFetch 是异步的,结果不应该立即可用。使用组合 API,结果应该按以下方式访问:

watch(loading, loadingValue => {
  if (!loadingValue)
    console.error(error.value)
})

或者,可以将挂钩修改为 return 一个可以链接的承诺,这与组合正交 API 但它用于组合钩子结果与承诺控制流:

  ...
  const promise = fetch()
  return { status, error, data, loading, promise }
  ...

onMounted(async () => {
  await promise
  console.error(error.value)
})