我試圖確定 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 代碼的示例
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:請(qǐng)注意,因?yàn)檫@個(gè)
client-only
標(biāo)記只會(huì)跳過(guò)渲染,而不是執(zhí)行,如 此處解釋。
某些軟件包在導(dǎo)入時(shí)不支持 SSR,為此您可以:
- 在動(dòng)態(tài)導(dǎo)入中使用條件(如果稍后要使用該庫(kù))
- 直接像這樣(如果你想加載像
vue-editor
這樣的組件)李>export default { components: { [process.client && 'VueEditor']: () => import('vue2-editor'), } }