SSR下如何正确处理Vue组件中的window对象访问?
我在用Nuxt做服务端渲染时,有个组件需要读取window.innerWidth,但一刷新页面就报“window is not defined”错误。本地开发没问题,部署到服务器就挂了。是不是得加判断?但我试了process.client也不太对。
这是我的组件代码:
<script setup>
const screenWidth = ref(0)
onMounted(() => {
screenWidth.value = window.innerWidth
})
watchEffect(() => {
console.log('当前宽度:', screenWidth.value)
})
</script>
<template>
<div>屏幕宽度:{{ screenWidth }}px</div>
</template>
这段代码会在组件挂载后检查是否在客户端,如果是的话再访问 window.innerWidth,这样就不会在服务端渲染时报错了。希望这能解决你的问题!