首页 > 解决方案 > 如何修复导航器/窗口/文档在 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
}

标签: javascriptvue.jsnuxt.js

解决方案


这是修复的解决方案:

  • 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


推荐阅读