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

问题描述

我正在尝试使用 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。

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