Warm tip: This article is reproduced from serverfault.com, please click

javascript-vuepress 构建中的“未定义获取”

(javascript - "fetch is not defined" on vuepress build)

发布于 2021-02-01 05:56:51

我正在尝试使用 vuepress 构建一个静态站点。我有一个使用 javascriptfetch的 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 方法。

Questioner
JKing
Viewed
0
Jay Li 2021-02-01 16:28:51

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

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