【问题标题】:Vue Composition Api .value returns nullVue Composition Api .value 返回 null
【发布时间】:2021-07-22 06:47:15
【问题描述】:

我有一个像这样的“可组合” 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(error)时,我可以清楚地看到

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

但如果我执行 console.error(error.value),它会返回 null。

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

【问题讨论】:

标签: vue.js axios vue-composition-api


【解决方案1】:

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

useFetch 是异步的,结果不应该立即可用。使用组合 API,结果应该被访问为:

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

或者,可以修改钩子以返回一个可以链接的承诺,这与组合 API 正交,但可以使用承诺控制流组合钩子结果:

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

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

【讨论】:

  • 你说得对!非常感谢。现在更有意义了!
猜你喜欢
  • 2022-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
  • 2020-06-16
  • 2021-04-26
  • 1970-01-01
  • 2020-12-11
相关资源
最近更新 更多