Nuxt JS-未定义窗口或文档

时间:2020-02-09 08:45:36

标签: nuxt.js

我已经看到许多与此主题相关的问题。但是他们都没有解决我的问题。

我遇到一种情况,必须检查窗口的innerWidth,以使用isMobile变量检查设备是否可移动。

<div v-if="isMobile" class="stores">
   <p class="text-uppercase text-muted mb-0 mt-4">
      ...
   </p>
</div>

下面是我的脚本代码。我正在检查process.client,但它以false的形式出现。我不知道是否错过了需要在(也许是nuxt.config.js)处添加的内容。

    data() {
      return {
        isMobile: false,
      };
    },
    mounted() {
      if (process.client) {
        console.log("Hello from the client!");
        this.isMobile = window.innerWidth < 768;
      }
      console.log('process', process.client); // Logs as false
    },

enter image description here

1 个答案:

答案 0 :(得分:1)

您的代码没有错。它可以正常工作。让我解释一下。

您在控制台Nuxt SSR中看到该文本吗?这意味着下面的输出是console.log在服务器端而不是在客户端执行的结果。如果您在控制台中查看此Nuxt SSR块下面的内容,您会看到另一个输出-process falseprocess true,具体取决于您当前窗口的宽度。

不确信?尝试以此替换该代码,我想您会相信我的。

created() {
  if (process.client) {
    console.log("Hello from the client!")
  }
  console.log("Hello from the server... and also the client!")
}

它应该输出这个。

enter image description here

也许您想用created()替换mounted()函数,因为在服务器端和客户端都调用了created()。并且mounted()仅在安装该组件/页面时在客户端调用。这样您就不必检查服务器端的process.client是否为true。始终为false,因此没有必要进行检查。