gpt4 book ai didi

javascript - 如何修复导航器/窗口/文档在 Nuxt 中未定义

转载 作者:行者123 更新时间:2023-12-05 00:44:10 27 4
gpt4 key购买 nike

我试图在 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

PS:mounted + process.client有点多余,因为 mounted仅在 the client 上运行.


另外,将您的组件包装到 <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

PS:小心因为这client-only标签只会跳过渲染,而不是执行,如 explained here .


当您导入某些软件包时,它们不支持 SSR,因为您可以:

  • 使用带有 dynamic import 的条件(如果该库打算稍后使用)
  • 直接这样(如果你想加载像 vue-editor 这样的组件)
export default {
components: {
[process.client && 'VueEditor']: () => import('vue2-editor'),
}
}

关于javascript - 如何修复导航器/窗口/文档在 Nuxt 中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67751476/

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