未使用Vue CLI仅通过CDN引入时,滚动事件内调用cargarLista报is not a function错误
问题根本原因
报错本质是普通事件回调的this指向丢失。
mounted钩子内,Vue会将组件实例绑定到当前函数作用域的this上,直接调用this.cargarLista()时能正常匹配到实例上的方法,因此无报错。- 你传入jQuery
.scroll()、原生addEventListener()的回调是通过普通function定义的函数,这类函数执行时的this会被自动绑定到事件触发的DOM对象(即window),而非Vue实例。此时调用this.cargarLista,实际是在查找window.cargarLista,该方法不存在,因此抛出类型错误。
之前项目能正常运行,大概率是旧代码中手动缓存了Vue实例的引用(如const that = this)或使用了箭头函数,迁移到当前项目时遗漏了这部分逻辑。
修复方案
方案1:缓存Vue实例引用
在mounted钩子开头将当前Vue实例存为局部变量,滚动回调内直接通过该变量调用方法,不依赖回调自身的this指向。
jQuery版本修复代码:
mounted() { // 缓存当前Vue实例 const vm = this vm.cargarLista(); $(window).scroll(function () { if ($(window).scrollTop() + $(window).height() == $(document).height()) { vm.cargarLista(); } }); },
原生JS版本修复代码:
mounted() { const vm = this window.addEventListener('scroll', function() { // 替换原代码中未定义的w/e/g变量 const windowHeight = window.innerHeight || document.documentElement.clientHeight; const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0; const body = document.body; const html = document.documentElement; const docHeight = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight ); // 加1px容错阈值,避免因尺寸偏差导致触底判断失效 if (scrollTop + windowHeight >= docHeight - 1) { vm.cargarLista(); } }); },
方案2:使用箭头函数编写滚动回调
箭头函数不存在自身的this绑定,会继承外层作用域的this(即mounted钩子作用域下的Vue实例),无需额外缓存变量。
jQuery版本修复代码:
mounted() { this.cargarLista(); $(window).scroll(() => { if ($(window).scrollTop() + $(window).height() == $(document).height()) { this.cargarLista(); } }); },
原生JS版本修复代码:
mounted() { window.addEventListener('scroll', () => { const windowHeight = window.innerHeight; const scrollTop = window.pageYOffset; const docHeight = Math.max( document.body.scrollHeight, document.documentElement.scrollHeight ); if (scrollTop + windowHeight >= docHeight - 1) { this.cargarLista(); } }); },
补充注意事项
- 因项目使用CDN引入Vue、业务代码拆分在独立JS文件中,需确保
cargarLista是定义在Vue实例methods选项内的方法,而非外部全局作用域的函数,否则即使this指向正确也会匹配不到方法。 - 建议为滚动触底逻辑增加防抖,避免滚动过程中短时间内重复触发
cargarLista,造成无意义的接口请求。 - 组件销毁时需移除绑定的滚动事件监听,避免内存泄漏:
methods: { // 将滚动回调定义为独立的实例方法,方便后续移除监听 handleScroll() { // 滚动判断逻辑 }, cargarLista() { // 列表加载逻辑 } }, mounted() { window.addEventListener('scroll', this.handleScroll) }, beforeUnmount() { window.removeEventListener('scroll', this.handleScroll) }
内容的提问来源于stack exchange,提问作者Felizx Fell
相关产品推荐
相关产品推荐

