Vue3 SSR环境报错IntersectionObserver is not defined问题求助
问题原因
IntersectionObserver 属于浏览器专属的Web API,仅在浏览器运行环境中存在,Node.js 原生没有提供该 API 实现。
你的代码将 new IntersectionObserver() 写在了模块顶层作用域,SSR 阶段会在服务端(Node.js环境)提前执行该模块代码,直接触发变量未定义的报错;常规客户端构建的代码全程在浏览器环境运行,自然可以正常调用该API。
修复方案
- 不要在顶层作用域初始化 IntersectionObserver 实例,将初始化和指令逻辑包裹在客户端环境判断的分支中,绝大多数SSR框架都会提供环境标识变量,比如
process.client、import.meta.env.SSR可用于判断当前运行环境。 - 滚动动画属于纯前端交互逻辑,服务端渲染阶段不需要处理,直接跳过相关逻辑即可,不会影响服务端输出的HTML结构正确性。
修改后代码示例
export default boot(async ({ app, isClient }) => { // 仅在客户端环境执行相关逻辑 if (!isClient) return const animatedScrollObserver = new IntersectionObserver( (entries, animatedScrollObserver) => { entries.forEach((entry) => { if (entry.isIntersecting) { entry.target.classList.add('enter'); animatedScrollObserver.unobserve(entry.target); } }); } ); app.directive('scrollanimation', { beforeMount(el) { el.classList.add('before-enter'); animatedScrollObserver.observe(el); } }) })
内容的提问来源于stack exchange,提问作者hpa
相关产品推荐
相关产品推荐

