【问题标题】:"fetch is not defined" on vuepress buildvuepress 构建上的“未定义获取”
【发布时间】:2021-05-05 08:10:24
【问题描述】:

我正在尝试使用 vuepress 构建一个静态站点。我有一个使用 javascript fetch 库的 vue 组件。它看起来像这样:

<template>
<div>
    <p> {{totalVuePackages}} </p>
</div>
</template>

<script>
export default {
  name: "get-request",
  data() {
    return {
      totalVuePackages: null
    };
  },
  created() {
    fetch("https://api.npms.io/v2/search?q=vue")
      .then(response => response.json())
      .then(data => (this.totalVuePackages = data.total));
  }
};
</script>

如果我使用vuepress dev,它可以完美运行,没有错误。但是,当我使用 vuepress build 时,会出现以下错误:

ReferenceError: fetch is not defined

我是 vue 和 javascript 的新手,但我假设 fetch 是在客户端运行的内置 javascript 方法。

【问题讨论】:

  • 如果您尝试使用内置的fetch - 为什么要包含另一个fetch 库?

标签: javascript vue.js fetch vuepress


【解决方案1】:

构建过程是在节点环境而不是浏览器中完成的,这就是未定义 fetch 的原因。

vuepress 调用 created 钩子来生成静态 html 文件。 如果你只想在客户端调用 fetch,你应该在 mounted 钩子上调用它,而不是在构建过程中调用它。

【讨论】:

    猜你喜欢
    • 2021-04-26
    • 1970-01-01
    • 2020-11-30
    • 2014-09-06
    • 2016-04-04
    • 2021-02-07
    • 2019-08-29
    • 2015-12-18
    • 1970-01-01
    相关资源
    最近更新 更多