【问题标题】:Async/Await in Vue with mount() hook not workingVue中的异步/等待,mount()钩子不起作用
【发布时间】:2020-11-20 16:43:16
【问题描述】:

我正在使用 vue 2.5,并且我有一个挂载钩子,它调用一个模块,该模块获取 API nedpoint 并通过挂载钩子将其返回给 vue 组件。我之前曾提出问题并被提及return response from async call 帖子并在回答中遵循示例,但我的 Vue 组件变量在组件渲染时仍显示为未定义。这是我的代码:

/modules/retrieveLeagueLeaders

 const getLeagueLeaders =  (url, params) => {
    fetch(url + new URLSearchParams(params), {
      method: "get",
      headers: {
        Authorization:
          "Basic ****=",
      },
    })
      .then((response) => response.json())
      .then((data) => {
        let leagueLeaders = data;
        console.log(
          "leagueLeaders is %s",
          leagueLeaders.cumulativeplayerstats.playerstatsentry[0].player
            .LastName
        );

        return leagueLeaders;
        
      });

    
  };

  module.exports = getLeagueLeaders;

和 Vue 代码:

/src/components/leagueLeaders
 mounted: async function () {
      this.qbLeaders = await getLeagueLeaders(this.fetchQbUrl, this.params);
      console.log("qBLeaders is %s", this.qbLeaders);
    },
  })

主机节目

qBLeaders is undefined nflLeagueLeaders.js:28
leagueLeaders is Wilson getLeagueLeaders.js:17

我尝试将整个模块包装在一个 Promise 中,但它在运行时仍然没有返回一个 Promise。我在 Vue 挂载钩子中使用 Async/Await 的方式有什么不正确的吗?我真的可以使用一些指导,因为我尝试了帖子中的所有建议都无济于事。提前谢谢..

【问题讨论】:

  • 您的getLeagueLeaders() 函数没有返回任何内容。

标签: javascript vue.js es6-promise


【解决方案1】:

不要尝试在回调中返回值,这不起作用,你可以简单地返回承诺:

const getLeagueLeaders =  (url, params) => {
   return  fetch(url + new URLSearchParams(params), {
      method: "get",
      headers: {
        Authorization:
          "Basic ****=",
      },
    })
      .then((response) => response.json())
         
  };

  module.exports = getLeagueLeaders;

【讨论】:

  • 谢谢!简短而准确。我现在偶然发现了一种类似的方法,但你的方法更短更优雅。我以为您必须将 response.json() 分配给某些东西,然后将其返回。那么 response.json() 是 Promise 的隐含解析值吗?
  • 这是我的荣幸
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-06
  • 2023-04-07
  • 2020-03-31
  • 2023-03-16
  • 2018-01-27
相关资源
最近更新 更多