我試圖確定 Nuxt 應(yīng)用程式內(nèi)的 UserAgent 和 Retina 資訊。但應(yīng)用程式拋出錯(cuò)誤並顯示導(dǎo)航/視窗未定義。我如何在 nuxt 應(yīng)用程式中獲取這些資訊?
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 }
這是要修復(fù)的解決方案:
navigator 未定義
window 未定義
#文件未定義
#這是一個(gè)關(guān)於如何包裝邏輯 JS 程式碼的範(fàn)例
sssccc
如下:https://nuxtjs.org/docs/2。 x/internals-glossary/context
PS: mounted
process.client
有點(diǎn)多餘,因?yàn)?mounted
只運(yùn)行在 客戶端。
此外,如果您希望元件僅在客戶端呈現(xiàn),則將元件包裝到 <client-only>
也是一個(gè)好主意。
this will be rendered on both: server + client
this one will only be rendered on client
此文件的文檔位於:https://nuxtjs.org/docs/2.x/features/nuxt-components/#the-client-only-component
#PS:請注意,因?yàn)檫@個(gè)
client-only
標(biāo)記只會(huì)跳過渲染,而不是執(zhí)行,如 此處解釋。
某些軟體套件在匯入時(shí)不支援 SSR,為此您可以:
- 在動(dòng)態(tài)導(dǎo)入中使用條件(如果稍後要使用該庫)
- 直接像這樣(如果你想載入像
vue-editor
這樣的元件)李>export default { components: { [process.client && 'VueEditor']: () => import('vue2-editor'), } }