gpt4 book ai didi

nuxt.js - Nuxt js - 未定义窗口或文档

转载 作者:行者123 更新时间:2023-12-04 10:36:52 27 4
gpt4 key购买 nike

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

我有一个情况,我必须检查 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

最佳答案

你的代码没有任何问题。它可以正常工作。让我解释。

您是否在控制台中看到该文本 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.clienttrue在服务器端。这将永远是 false所以没有必要做那个检查。

关于nuxt.js - Nuxt js - 未定义窗口或文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60134881/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com