如何在Nuxt+TypeScript中为特定div添加滚动事件监听器
Nuxt.js + TypeScript 实现特定Div滚动加载
转换后的TypeScript组件代码
结合你的Nuxt项目现有配置(已安装nuxt-property-decorator),将原代码转为类组件形式,同时优化DOM元素获取方式(使用Vue的ref替代原生querySelector):
<template> <div id="app"> <div id="infinite-list" ref="infiniteList" style="height: 300px; overflow-y: auto; border: 1px solid #ccc;"> <div v-for="item in items" :key="item" class="list-item"> {{ item }} </div> <div v-if="loading" class="loading">加载中...</div> </div> </div> </template> <script lang="ts"> import { Component, Vue, Ref, Data } from 'nuxt-property-decorator'; @Component export default class InfiniteScroll extends Vue { @Data() loading = false; @Data() nextItem = 1; @Data() items: string[] = []; @Ref('infiniteList') infiniteList!: HTMLDivElement; mounted() { this.infiniteList.addEventListener('scroll', this.handleScroll); this.loadMore(); } beforeDestroy() { // 移除监听避免内存泄漏 this.infiniteList.removeEventListener('scroll', this.handleScroll); } handleScroll() { const { scrollTop, clientHeight, scrollHeight } = this.infiniteList; if (scrollTop + clientHeight >= scrollHeight) { this.loadMore(); } } loadMore() { this.loading = true; setTimeout(() => { for (let i = 0; i < 20; i++) { this.items.push(`Item ${this.nextItem++}`); } this.loading = false; }, 200); } } </script> <style scoped> .list-item { padding: 10px; border-bottom: 1px solid #eee; } .loading { text-align: center; padding: 10px; color: #666; } </style>
关键说明
- 使用
@Ref装饰器获取DOM元素,替代原生document.querySelector,更符合Vue组件规范 - 通过
@Data装饰器声明响应式数据,为items指定string[]类型保证类型安全 - 将滚动监听逻辑抽离为独立方法
handleScroll,方便组件销毁时移除监听,避免内存泄漏 - 所有逻辑遵循TypeScript语法规范,适配Nuxt的TS运行环境
项目依赖适配
你的package.json已包含所需的TypeScript相关依赖:
@nuxt/typescript-runtime和@nuxt/typescript-build提供Nuxt的TypeScript基础支持nuxt-property-decorator支持类组件语法(如@Component、@Data、@Ref)
无需额外安装依赖,直接使用上述代码即可。
内容的提问来源于stack exchange,提问作者ash
相关产品推荐
相关产品推荐

