【问题标题】:Vue-Select: How can I convert this fetch() code to use axios?Vue-Select:如何将此 fetch() 代码转换为使用 axios?
【发布时间】:2022-01-15 18:31:55
【问题描述】:

我正在尝试在我的应用程序中使用 vue-select 包。我有一些从文档中复制的代码,它工作正常。但是,为了便于阅读,我想将其转换为使用 axios 而不是 fetch(),这样我也可以使用自己的 axios 配置设置。

如何将以下代码转换为使用 axios 而不是 fetch?

    search: debounce((loading, search, vm) => {
      fetch(
        `https://api.github.com/search/repositories?q=${escape(search)}`
      ).then((res) => {
        res.json().then((json) => (vm.options = json.items))
        loading(false)
      })
    }, 350)

我尝试了以下代码,但出现错误:Uncaught (in promise) TypeError: res is not a function:

    search: debounce(async (loading, search, vm) => {
      await axios
        .get(`https://api.github.com/search/repositories?q=${escape(search)}`)
        .then((res) => {
          res((json) => (vm.options = json.items))
          loading(false)
        })
    }, 350)

【问题讨论】:

    标签: vuejs2 axios vue-select


    【解决方案1】:

    res() 是一个对象时,您将其作为函数调用。您可能是指来自 fetch 的 res.json()。对于 axios,这应该不是必需的,您可以 access the jsonres.data

    您还混合了 Promise/async,令人惊讶的是它不会引发错误(.then() 不应在等待后定义),但会使代码难以阅读。使用其中一种。

    异步

    {
        search: debounce(async (loading, search, vm) => {
            let res = await axios.get(`https://api.github.com/search/repositories?q=${escape(search)}`)
            const items = res.data
            vm.options = items
            loading(false)
        }, 350)
    }
    

    承诺

    { 
        search: debounce((loading, search, vm) => {
            axios
                .get(`https://api.github.com/search/repositories?q=${escape(search)}`)
                .then((res) => {
                    const items = res.data
                    vm.options = items
                    loading(false)
                })
        }, 350)
    }
    

    IMO 我发现 fetch() 更易于阅读,而且它具有原生支持。

    【讨论】:

      猜你喜欢
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      • 2020-08-17
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多