javascript - 如何修复导航器/窗口/文档在 Nuxt 中未定义
问题描述
我试图在 Nuxt 应用程序中确定 UserAgent 和 Retina 信息。但是应用程序抛出错误并显示导航器/窗口未定义。如何在 nuxt 应用程序中获取这些信息?
const userAgent = navigator.userAgent.toLowerCase()
const isAndroid = userAgent.includes('android')
isRetina() {
let mediaQuery
if (typeof window !== 'undefined' && window !== null) {
mediaQuery =
'(-webkit-min-device-pixel-ratio: 1.25), (min--moz-device-pixel-ratio: 1.25), (-o-min-device-pixel-ratio: 5/4), (min-resolution: 1.25dppx)'
if (window.devicePixelRatio > 1.25) {
return true
}
if (window.matchMedia && window.matchMedia(mediaQuery).matches) {
return true
}
}
return false
}
解决方案
这是修复的解决方案:
navigator is undefined
window is undefined
document is not defined
这是一个关于如何包装逻辑 JS 代码的示例
<script>
import { jsPlumb } from 'jsplumb' // client-side library only, no SSR support
export default {
mounted() {
if (process.client) {
// your JS code here like >> jsPlumb.ready(function () {})
}
},
}
</script>
如此处所示:https ://nuxtjs.org/docs/2.x/internals-glossary/context
此外,如果您希望它仅在客户端呈现,则将组件包装到<client-only>
其中也是一个好主意。
<template>
<div>
<p>this will be rendered on both: server + client</p>
<client-only>
<p>this one will only be rendered on client</p>
</client-only>
<div>
</template>
这个文档在这里:https ://nuxtjs.org/docs/2.x/features/nuxt-components/#the-client-only-component
推荐阅读
- excel - 如何根据特定条件突出显示散点图(Excel)中的特定数据点?
- python - 检查单词是否在一个系列中,然后从字符串中删除它
- android-memory - android 如何动态获取应用程序的内存使用情况,例如使用 android studio profiler 显示
- sass - 使用包含斜杠和冒号的属性选择器时出现重复的 CSS 排除
- android - 如何处理在 android kotlin 中上传文件的改造套接字超时?
- python - 将包含字符串和 int 对象的列表转换为字节数组以进行套接字通信
- excel - 将行从一张纸复制到另一张带有多个表格的表格
- java - 使用未更新的 JButton 更改 JFrame 背景颜色
- python - 将 2 个 for 循环中的代码合并到 1 个 for 循环中
- python - 如何对多项式样本进行 Tukey 风格比例检验?