Heim  >  Fragen und Antworten  >  Hauptteil

Korrigieren Sie die undefinierte Methode „Navigator/Fenster/Dokument“ in Nuxt

Ich versuche, die UserAgent- und Retina-Informationen in einer Nuxt-Anwendung zu ermitteln. Aber die Anwendung gibt einen Fehler aus und sagt, dass Navigation/Fenster nicht definiert ist. Wie erhalte ich diese Informationen in einer Nuxt-Anwendung?

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
}

P粉143640496P粉143640496207 Tage vor381

Antworte allen(1)Ich werde antworten

  • P粉242126786

    P粉2421267862024-03-26 16:45:25

    这是要修复的解决方案:

    • navigator 未定义
    • window 未定义
    • 文档未定义

    这是一个关于如何包装逻辑 JS 代码的示例

    
    

    如下所示:https://nuxtjs.org/docs/2。 x/internals-glossary/context

    PS: mounted + process.client 有点多余,因为 mounted 仅运行在 客户端


    此外,如果您希望组件仅在客户端呈现,则将组件包装到 <client-only> 也是一个好主意。

    
    

    此文档的文档位于:https://nuxtjs.org/docs/2.x/features/nuxt-components/#the-client-only-component

    PS:请注意,因为这个 client-only 标记只会跳过渲染,而不是执行,如 此处解释


    某些软件包在导入时不支持 SSR,为此您可以:

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

    Antwort
    0
  • StornierenAntwort