如何修复 Nuxt 中导航器/窗口/文档未定义的问题

Tan*_*man 5 javascript vue.js nuxt.js

我试图确定 Nuxt 应用程序内的 UserAgent 和 Retina 信息。但应用程序抛出错误并显示导航/窗口未定义。我如何在 nuxt 应用程序中获取这些信息?

const userAgent = navigator.userAgent.toLowerCase()
const isAndroid = userAgent.includes('android')
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)

kis*_*ssu 15

这是要修复的解决方案:

  • 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>
Run Code Online (Sandbox Code Playgroud)

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

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


另外,<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>
Run Code Online (Sandbox Code Playgroud)

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

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


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

export default {
  components: {
    [process.client && 'VueEditor']: () => import('vue2-editor'),
  }
}
Run Code Online (Sandbox Code Playgroud)