Home  >  Article  >  Web Front-end  >  Why Are Navigator, Window, and Document Undefined in My Nuxt App?

Why Are Navigator, Window, and Document Undefined in My Nuxt App?

DDD
DDDOriginal
2024-11-11 15:16:02612browse

Why Are Navigator, Window, and Document Undefined in My Nuxt App?

How to Address undefined Error on Navigator/Window/Document in Nuxt

When attempting to retrieve user agent or retina information within a Nuxt application, errors may arise indicating that navigator, window, or document are undefined. This occurs due to JavaScript code being executed during server-side rendering (SSR), which lacks access to browser-specific objects like window or navigator.

Solution

To resolve this issue, wrap your logic JS code within the following construct:

<script>
  import { jsPlumb } from 'jsplumb'

  export default {
    mounted() {
      if (process.client) {
        // Your JS code here, like: jsPlumb.ready(function () {})
      }
    },
  }
</script>

This ensures that your code only executes on the client-side, where these objects are available. Additionally, consider using the component to render specific sections solely on the client.

<template>
  <div>
    <p>Rendered on both: server + client</p>
    
    <client-only>
      <p>Rendered only on client</p>
    </client-only>
  </div>
</template>

Additional Tips

  • Check the library documentation for SSR support. If unsupported, use dynamic import or direct import.
  • For example:

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

    By employing these techniques, you can access navigator, window, and document objects within Nuxt applications and resolve the undefined errors encountered.

The above is the detailed content of Why Are Navigator, Window, and Document Undefined in My Nuxt App?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn