必须在 unmounted(vue 3)或 beforedestroy(vue 2)中用同一命名函数引用移除 scroll 监听器,禁用箭头函数或 bind,否则无法清除导致内存泄漏和报错。

在 Vue Options API 中,要在组件销毁时手动移除全局窗口滚动监听,关键是在 mounted 中添加监听器,在 beforeDestroy(Vue 2)或 unmounted(Vue 3 Options API 兼容写法)中对应移除——且必须使用同一函数引用。
确保 handler 是命名函数,不可用箭头函数或内联写法
因为 removeEventListener 要求传入的回调函数与 addEventListener 时完全相同(引用相等)。箭头函数每次都会生成新实例,导致无法匹配移除。
- ✅ 正确:定义为 methods 中的命名方法
- ❌ 错误:
window.addEventListener('scroll', () => { ... })或window.addEventListener('scroll', this.handleScroll.bind(this))
Vue 2 写法(推荐 beforeDestroy)
在组件选项中按如下方式组织:
export default {
data() {
return {
isScrolledToBottom: false
}
},
methods: {
handleScroll() {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
const windowHeight = window.innerHeight
const scrollHeight = document.documentElement.scrollHeight
if (scrollTop + windowHeight >= scrollHeight - 5) {
this.isScrolledToBottom = true
}
}
},
mounted() {
window.addEventListener('scroll', this.handleScroll)
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll)
}
}
Vue 3 Options API(兼容写法)
若项目已升级 Vue 3 但仍用 Options API,建议使用 unmounted(更语义清晰,且 Vue 2.7+ 也支持):
使用 `@ainative/vue-sdk` 为 Vue 3 应用添加 AI 聊天功能。适用于以下场景:(1) 安装 `@ainative/vue-sdk`,(2) 在 Vue 组件中使用 `useChat` 组合式函数,(3) 提供……
-
beforeDestroy在 Vue 3 中已被废弃,unmounted是标准替代 - 两者逻辑一致,但
unmounted更符合当前规范
示例:
export default {
// ... data、methods 同上
mounted() {
window.addEventListener('scroll', this.handleScroll)
},
unmounted() {
window.removeEventListener('scroll', this.handleScroll)
}
}
额外提醒:避免监听器残留的细节
即使组件已卸载,未清理的 scroll 监听器仍会持续执行,可能引发:
- 访问已销毁组件的
this.xxx报Cannot read property 'xxx' of null - 重复触发逻辑(如多次加载分页)
- 内存泄漏(闭包持有组件实例)
所以移除动作不是“可选优化”,而是必须完成的资源释放步骤。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










