Nuxt.js - window或document未定义。

4

我看到很多与此主题相关的问题,但没有一个可以解决我的问题。

我有一个情况,需要检查窗口的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个回答

5

你的代码没有问题,它按照应有的方式运行。让我来解释下。

你在控制台中看到的那个文本 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

也许您想用 mounted() 函数替换 created() 函数,因为 created() 在服务器端和客户端都会调用。而 mounted() 只在客户端调用,当组件/页面被挂载时。所以您不需要在服务器端检查是否 process.clienttrue。因为它始终是 false,所以无需进行此检查。


我已经在mounted下进行了更改和检查,但是我无法看到来自Hello from client的任何日志。 - Yashwardhan Pauranik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接