I'm trying to determine the UserAgent and Retina information within a Nuxt application. But the application throws an error and says navigation/window is undefined. How do I get this information in a nuxt application?
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粉2421267862024-03-26 16:45:25
This is the solution to fix:
navigator undefined
window undefined
Document not defined
This is an example on how to wrap logical JS code
sssccc
As shown below: https://nuxtjs.org/docs/2. x/internals-glossary/context
PS: mounted
process.client
is a bit redundant, because mounted
only runs on the client.
Also, if you want the component to be rendered only on the client side, it is also a good idea to wrap the component in <client-only>
.
this will be rendered on both: server + client
this one will only be rendered on client
The documentation for this document is located at: https://nuxtjs.org/docs/2.x/features/nuxt-components/#the-client-only-component
PS: Please note that because of this
client-only
tag it will only skip rendering, not execution, as explained here.
Some packages do not support SSR when importing, for this you can:
- Use conditions in dynamic imports (if you want to use the library later)
- Directly like this (if you want to load a component like
vue-editor
) 李>export default { components: { [process.client && 'VueEditor']: () => import('vue2-editor'), } }reply0Cancel